Set ADT Specification
Here is the fully specified Set ADT:
/**
* A Set is a collection of distinct elements, with no order.
* @param <T> the type of elements in this set
*/
public interface Set<T> {
/**
* Adds an item to this set if it is not already present.
* @param item the item to be added to this set
* @return true if the item was added, false if it was already present
* @throws IllegalArgumentException if the item is null
*/
boolean add(T item);
/**
* Removes an item from this set if it is present.
* @param item the item to be removed from this set
* @return true if the item was removed, false if it was not present
* @throws IllegalArgumentException if the item is null
*/
boolean remove(T item);
/**
* Returns true if this set contains the given item.
* @param item the item to look for
* @return true if the item is in this set, false otherwise
* @throws IllegalArgumentException if the item is null
*/
boolean contains(T item);
/**
* Returns the number of items in this set.
* @return the number of items in this set
*/
int size();
}
The first three methods return a boolean, but the boolean does not mean the same thing for all three. For contains, the boolean just answers whether the item is in the set or not, and it leaves the set unchanged either way. For add and remove, the boolean reports whether the call changed the set. Notice that none of these methods throws a NoSuchElementException. If you add an item that is not in the set yet, add puts it in and returns true. If the item is already there, add does nothing and returns false. Likewise, if you remove an item that is in the set, remove takes it out and returns true. If the item is not there, remove does nothing and returns false.
The contract rejects only one value, and that is null. add, remove, and contains all reject a null argument with an IllegalArgumentException, because null is not a value we ever store in a set.
You can find a suite of tests for this interface in the SetTest class within the code accompanying this chapter.