Activity 5.8 - Using the Set interface

Topic

This activity uses the basic operations in the Set interface.

Materials

In addition to the Solution document, the project for this activity contains one class:

Task

First look up the Set<E> interface in the API documentation. The characteristic feature of a set is that the items are unique: the same element cannot appear more than once.

In this activity we shall concentrate on five basic operations:

Read carefully what these operations do. The Set interface has a number of other operations but they are not relevant to this activity.

Note that add and remove have boolean return type. These methods return true if the collection has changed i.e. the operation has been successful.

Instructions

  1. Add a statement to the SetTest class to import java.util.*..
    Then make the following changes to the code in main and re-run the project each time.

  2. Declare a variable of interface type

    Set<String> set1;

    (In what follows your variables should all be of interface type Set, not of class type HashSet or TreeSet. This is good practice, because it lets us alter what implementation we use just by using a different constructor, without any need to declare the variables afresh.)

    Add a statement to create an empty instance of HashSet using its zero-argument constructor and assign the new instance to set1, i.e.

    set1 = new HashSet<String>();

    Add statements to add an item to the set

    set1.add("Persuasion");

    and display the result

    System.out.println(set1);

    Run the project. Check that the output is as you would expect.

  3. Next introduce statements which will do the following:

    Run the project again. Check that the output is as you would expect.

  4. Next we use a constructor that takes an argument which is in itself a collection. Insert the statement

    Set<String> set2 = new TreeSet<String>(set1);

    This will create a tree set which contains all the elements belonging to the set referenced by set1. Add a statement that will print set2, and run the project. What is different about the output this time and why?

  5. Finally, add the code to remove all four elements from set2 (in any order you please) and check that the following statement produces the expected result:

    System.out.println(set2.isEmpty());