Java Reference
In-Depth Information
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-
ception whenyouattempttoremoveanentry(alsoknownasmapping)fromatree-
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-
ject argumentinsteadofacceptingonlyobjectswhosetypesarethoseofthecollec-
tion.Inotherwords,whyis remove() notdeclaredas boolean remove(E e) ?
Also,whyare containsAll() , removeAll() ,and retainAll() notdeclared
withanargumentoftype Collection<? extends E> ,toensurethatthecollec-
tionargumentonlycontainselementsofthesametypeasthecollectiononwhichthese
methods are called? The answer to these questions is the need to maintain backward
compatibility.TheCollectionsFrameworkwasintroducedbeforeJava5anditsintro-
duction of generics. To let legacy code written before version 5 continue to compile,
these four methods were declared with weaker type constraints.
Search WWH ::




Custom Search