THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1
Makes sure that this collection contains the object elem, returning true if
this required changing the collection. If this collection allows duplicates, add
will always return true. If duplicates are not allowed and an equivalent
element is already in the collection, add will return false. (Optional)

public booleanremove(Object elem)

Removes a single instance of elem from the collection, returning true if
this required changing the collection (that is, if the element existed in this
collection). If elem is null, returns TRue if there was a null element in
the collection. (Optional)

All methods that need the notion of equivalence (such as contains and remove) use the equals method
on the relevant objects.


The toArray method that has no parameters returns an array of Object. You can use toArray(T[]) to
create arrays of other types. For example, if your collection contains String objects, you may want to create
a String array. The following code will do that:


String[] strings = new String[collection.size()];
strings = collection.toArray(strings);


Notice that strings is assigned the return value of toArray. This is to be safe in case the size of the
collection has increased since the array was allocated, in which case the returned array will not be the one
originally allocated. You can also use an empty String array to pass in the desired type and let toArray
allocate an array of exactly the right size:


String[] strings = collection.toArray(new String[0]);


Several methods of Collection operate in bulk from another collection. The methods are provided for
convenience; also, a collection can often operate more efficiently in bulk.


public booleancontainsAll(Collection<?> coll)

Returns true if this collection contains each of the elements in coll.

public booleanaddAll(Collection<? extends E> coll)

Adds each element of coll to this collection, returning TRue if any addition
required changing the collection. (Optional)

public booleanremoveAll(Collection<?> coll)

Removes each element of coll from this collection, returning true if any
removal required changing the collection. (Optional)

public booleanretainAll(Collection<?> coll)

Removes from this collection all elements that are not elements of coll,
returning true if any removal required changing the collection. (Optional)
Free download pdf