442 Part II: The Java Library
a zero-based index. A list may contain duplicate elements.Listis a generic interface that has
this declaration:
interface List<E>
Here,Especifies the type of objects that the list will hold.
In addition to the methods defined byCollection,Listdefines some of its own, which
are summarized in Table 17-2. Note again that several of these methods will throw an
UnsupportedOperationExceptionif the list cannot be modified, and aClassCastExceptionis
Method Description
boolean add(Eobj) Addsobjto the invoking collection. Returnstrueifobjwas added
to the collection. Returnsfalseifobjis already a member of the
collection and the collection does not allow duplicates.
boolean addAll(Collection<? extends E>c) Adds all the elements ofcto the invoking collection. Returnstrue
if the operation succeeded (i.e., the elements were added).
Other wise, returnsfalse.
void clear( ) Removes all elements from the invoking collection.
boolean contains(Objectobj) Returnstrueifobjis an element of the invoking collection.
Other wise, returnsfalse.
boolean containsAll(Collection<?>c) Returnstrueif the invoking collection contains all elements
ofc.Other wise, returnsfalse.
boolean equals(Objectobj) Returnstrueif the invoking collection andobjare equal.
Other wise, returnsfalse.
int hashCode( ) Returns the hash code for the invoking collection.
boolean isEmpty( ) Returnstrueif the invoking collection is empty. Other wise,
returnsfalse.
Iterator<E> iterator( ) Returns an iterator for the invoking collection.
boolean remove(Objectobj) Removes one instance ofobjfrom the invoking collection. Returns
trueif the element was removed. Other wise, returnsfalse.
boolean removeAll(Collection<?>c) Removes all elements ofcfrom the invoking collection. Returns
trueif the collection changed (i.e., elements were removed).
Other wise, returnsfalse.
boolean retainAll(Collection<?>c) Removes all elements from the invoking collection except those
inc.Returnstrueif the collection changed (i.e., elements were
removed). Other wise, returnsfalse.
int size( ) Returns the number of elements held in the invoking collection.
Object[ ] toArray( ) Returns an array that contains all the elements stored in the
invoking collection. The array elements are copies of the
collection elements.
<T> T[ ] toArray(Tarray[ ]) Returns an array that contains the elements of the invoking
collection. The array elements are copies of the collection
elements. If the size ofarrayequals the number of elements,
these are returned inarray.If the size ofarrayis less than the
number of elements, a new array of the necessar y size is allocated
and returned. If the size ofarrayis greater than the number of
elements, the array element following the last collection element
is set tonull.AnArrayStoreExceptionis thrown if any collection
element has a type that is not a subtype ofarray.
TABLE 17-1 The Methods Defined byCollection