CSc 103 Activity

Exploring sets in the Java Collections Framework.



Study the HashSet API
Create a Java program to perform the following tasks using HashSet.


  1. Construct a HashSet of Integers and add four Integers to it.  Print the HashSet using its default toString() method.

  2. Print the HashSet by iterating over it's contents (use for-each loop).

  3. Write code that shows that duplicates can not be added to a set.


  4. Construct a HashSet of Strings and add the strings "ape", "cat", and "bat" to it.

  5. Construct a second HashSet of Strings and add the strings "bat", "fox" and "ape".

  6. Print out the union of the two sets.
    Print out the intersection of the two sets.
    Print out the difference of the two sets.
    (If you don't know how to do this, read the assigned readings for today.)

  7. Write code to show that the intersection (above) is a subset of the union.


  8. Construct a HashSet of Strings and add the strings "cat", "ape", "dog", and "bat" to it.

  9. Print the number of items in the set.

  10. Write a selection statement that prints "Found" if "dog" is in the set, or "absent" if it isn't.

  11. Remove "dog" from the set,  then repeat the selection statement above.

Put each student's name in the class header comment. Print your completed source code and a sample execution output and submit it on the instructor's table before the start of the next class meeting (one per team). No other writeup is needed.



Extra Credit Lab

This is an individual activity.

Follow the directions to create an account on UVa Online Judge.
Complete problem 496 Simply Subsets.

You should use HashSet in your solution.

When the online judge gives you an "Accepted" verdict, printout your source code, write your UVa username on top, and bring it to class to submit. Due at the next class meeting.