Sets
- Models a mathematical set; hence, no duplicates are allowed
-
boolean contains(Object o)
returns true if the object is
present; false otherwise
-
boolean add(Object o)
returns true if the add is successful,
which happens if the object was not already present
-
boolean remove(Object o)
returns true if the object was
there to be removed; returns false if the object was not there
-
HashSet
is constant time in the average case for all three
operations; it can be linear in the (rare) worst case
- equals() defaults to doing a reference comparison
- hashCode() defaults to using the reference
- If equals() is true for two objects, then hashCode() needs to return
the same value for them
- Hence, when using HashSet, make sure that if equals() has been
overridden for the object, that hashCode() is also overridden in a
consistent manner
-
LinkedHashSet
is slightly less efficient for the above
operations, but it is more efficient when iterated
-
TreeSet
is O(log n) for all three operations
- Only objects that implement the Comparable interface can be used
- Implements the
SortedSet
interface, which means that
first and last elements can be requested, and consecutive subsets can
be requested
(next)