Lab 12: Sets
David Levine
Computer Science Department
St. Bonaventure University
Copyright, 2004

 

Objective:

This lab introduces gives you some practice with Sets.  There is no "application" per se, but rather the purpose is to explore the Set class from within Java.

 

Background:

This lab is based on the following sections from Weiss:
            6.7 – Sets

A set stores a collection of objects.  A set differs from, a list in that a set is not ordered, nor can it have the same element in it more than once.

 

Instructions:

1.     Begin by opening the Java API and examining the methods that a Set supports.  How many methods are there?  Examine the TreeSet and HashSet classes.  Do they contain the same methods?  Can you explain things are as they are?

2.   Build a simple Eclipse project named SetTest.  This project will have only one class which will serve as a "testing bed" for your experiments with Sets.  This class will (initially) have only a main method.  Begin by building a TreeSet consisting of five strings.  Have the Set printed out at the beginning, after adding all five strings, and again after adding the third string (that you added) another time.  [Note: you can print out the a set by simply putting it in a System.out.println() parameter list.]  What is the lesson here?

3.     Now repeat the operation, but use a HashSet instead of a TreeSet.  Explain any differences you notice.
 

4.     While it is possible to print a set as easily as in Step 1, it is more general  to print them using iterators.  By using almost exactly the same code as in the "iterator lab", you should be able to print the contents of your set using an iterator.  Do so by creating a new method named printSet that takes a Set as a parameter and then prints it out.  Modify your main method to call your new method rather than letting System.out.println do all the work.  How does the output compare to that which you previously reported?  Print your code at this point to hand in with lab.


5.     Sets can hold more than one type of object.  Modify your program to demonstrate this fact.  Explain how the printing operation works in this new world.  Print this version of your source code as well.

Hand in:

The write-up you hand in for this lab should include:

Help Policy:

Help Policy in Effect for This Assignment:  Group Project with Limited Collaboration

In particular, you may discuss the assignment and concepts related to the assignment with the following persons, in addition to an instructor in this course: any member of your group; any St. Bonaventure Computer Science instructor; and any student enrolled in CS 132. 

You may use the following materials produced by other students:  materials produced by members of your group.  

You may use the following materials produced by other students:  NONE.