Java Reference
In-Depth Information
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 boolean
containsAll(Collection<?> coll)
Returns
true
if this collection contains each of the elements in
coll
.
public boolean
addAll(Collection<? extends E> coll)
Adds each element of
coll
to this collection, returning
TRue
if
any addition required changing the collection. (Optional)
public boolean
removeAll(Collection<?> coll)