Answers to Self-Study Questions

Test Yourself #1

Question 1:

If an item is already a member of the set, you could throw an exception. But, you may decide for performance reasons to simply ignore the attempt to add.

From Java's Set.add() documentation:

If this set already contains the element, the call leaves the set unchanged and returns false. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements.

Question 2:

static Set union(Set<E> set1, Set<E> set2) returns a new Set with the elements of set1 and set2.
static Set intersection(Set<E> set1, Set<E> set2) returns a new Set with only the elements found in both set1 and set2.

Java's Set interface does not require these operations. They are not fundamental for a collection that is a Set, but they are required for many set algorithms. In Java, they are left to the user of such types to determine their suitability and implementation details.

Question 3:

Most definitely, the equals() and hashCode() methods of a user-defined Set type must be overridden to ensure that the elements of two different sets are compared and not simply the object's address.

Test Yourself #2

Question 1:


Set plurals = new MySet();
for ( String word : words ) {
    plurals.add(word+"s");
}

Using Java's enhanced for loop is possible because Set implements Iterable and we are not attempting to add or remove elements from of words.

Question 2:

for ( String letter : vowels ) {
    letters.remove(letter);
}

The above is a solution. But, its indirect access to the internal data structure of the Set may mean that a more efficient solution is possible. If a remove(Set<E> set) method is defined, the Set's implementation can take advantage of the specific data structure they chose and ensure this problem is solved in O(V) time, where V is the number of elements in vowels.

Test Yourself #3

Question 1:

 
    // returns a Set that is the union of set A and set B
    // this implementation relies on the fact that 
    // the add method does not add duplicate items
    public static Set<E> union(Set<E> A, Set<E> B) { 
        Set<E> unionSet = new Set<E>();
        for ( E item : A ) { unionSet.add(item); }
        for ( E item : B ) { unionSet.add(item); }
        return unionSet;
    }  

Question 2:

    // returns a Set that is the intersection of set A and set B
    public static Set<E> intersection(Set <E> A, Setlt;E> B) { 
        Set<E> intersectionSet = new Set<E>();
        for ( E item : A ) {
            if ( B.contains(item) ) { intersectionSet.add(item); }
        }
        return intersectionSet;
    }