Methods such as add() , remove() , clear() , and retainAll()
that alter the collection were conceived of as optional parts of
the API. Unfortunately, they were specified a long time ago,
when the received wisdom was to indicate the absence of an
optional method by throwing UnsupportedOperation Excep
tion . Accordingly, some implementations (notably read-only
forms) may throw this unchecked exception.
Collection , Map , and their subinterfaces do not extend the Cloneable or Serializa
ble interfaces. All of the collection and map implementation classes provided in the
Java Collections Framework, however, do implement these interfaces.
Some collection implementations place restrictions on the elements that they can
contain. An implementation might prohibit null as an element, for example. And
EnumSet restricts membership to the values of a specified enumerated type.
Attempting to add a prohibited element to a collection always throws an unchecked
exception such as NullPointerException or ClassCastException . Checking
whether a collection contains a prohibited element may also throw such an excep‐
tion, or it may simply return false .
The Set Interface
A set is a collection of objects that does not allow duplicates: it may not contain two
references to the same object, two references to null , or references to two objects a
and b such that a.equals(b) . Most general-purpose Set implementations impose
no ordering on the elements of the set, but ordered sets are not prohibited (see Sor
tedSet and LinkedHashSet ). Sets are further distinguished from ordered collections
like lists by the general expectation that they have an efficient contains method
that runs in constant or logarithmic time.
Set defines no additional methods beyond those defined by Collection but places
additional restrictions on those methods. The add() and addAll() methods of a Set
are required to enforce the no-duplicates rules: they may not add an element to the
Set if the set already contains that element. Recall that the add() and addAll()
methods defined by the Collection interface return true if the call resulted in a
change to the collection and false if it did not. This return value is relevant for Set
objects because the no-duplicates restriction means that adding an element does not
always result in a change to the set.
Table 8-1 lists the implementations of the Set interface and summarizes their inter‐
nal representation, ordering characteristics, member restrictions, and the perfor‐
mance of the basic add() , remove() , and contains operations as well as iteration
performance. You can read more about each class in the reference section. Note that
CopyOnWriteArraySet is in the java.util.concurrent package; all the other
implementations are part of java.util . Also note that java.util.BitSet is not a
Set implementation. This legacy class is useful as a compact and efficient list of
boolean values but is not part of the Java Collections Framework.