Table 5-1 reveals three exceptional things about various Collection methods.
First, some methods can throw instances of the UnsupportedOperationExcep-
tion class. For example, add() throws UnsupportedOperationException
whenyouattempttoaddanobjecttoan immutable (unmodifiable)collection(discussed
later in this chapter).
Second, some of Collection 's methods can throw instances of the
ClassCastException class. For example, remove() throws ClassCastEx-
based map whose keys are String s, but specify a non- String key instead.
Finally, Collection 's add() and addAll() methods throw IllegalArgu-
mentException instanceswhensome property (attribute)oftheelementtobeadded
prevents it from being added to this collection. For example, a third-party collection
class's add() and addAll() methods might throw this exception when they detect
negative Integer values.
Note Perhaps you are wondering why remove() is declared to accept any Ob-
tion.Inotherwords,whyis remove() notdeclaredas boolean remove(E e) ?
Also,whyare containsAll() , removeAll() ,and retainAll() notdeclared
withanargumentoftype Collection<? extends E> ,toensurethatthecollec-
methods are called? The answer to these questions is the need to maintain backward
duction of generics. To let legacy code written before version 5 continue to compile,
these four methods were declared with weaker type constraints.