21.4. The Collection Interface
As you have seen, most collection types are subtypes of the Collection interface. The only exceptions are
those that are subtypes of Map. In this section we cover the Collection interface. The following sections
describe the interfaces that extend Collection and the specific collection implementations provided in
java.util. We leave Map and its related types for later. We also defer talking about implementing your
own collection types.
The basis of much of the collection system is the Collection interface. As you saw in Figure 21-1, most of
the actual collection types implement this interface, usually by implementing an extended interface such as
Set or List. So Collection is a good place to start understanding collections. It has the following
primary methods for working with an individual collection:
public intsize()
Returns the size of this collection, that is, the number of elements it currently
holds. The value returned is limited to Integer.MAX_VALUE even if the
collection holds more elements.
public booleanisEmpty()
Returns TRue if this collection currently holds no elements.
public booleancontains(Object elem)
Returns true if the collection contains the object elem; that is, if this
collection has an element on which invoking equals with elem returns
true. If elem is null, returns TRue if there is a null element in the
collection.
public Iterator<E>iterator()
Returns an iterator that steps through the elements of this collection.
public Object[]toArray()
Returns a new array that contains all the elements of this collection.
public <T> T[]toArray(T[] dest)
Returns an array that contains all the elements of this collection. If the
elements will fit in dest, then they are placed in dest and it is dest that is
returned. If dest has more elements than this collection, the first element in
dest that follows the contents of the collection is set to null to mark the
end of the collection. If the elements do not fit in dest, a new, larger array is
created of the same type as dest, filled in, and returned. If the type of dest
is not compatible all the elements in the collection, an
ArrayStoreException is thrown.
public booleanadd(E elem)