Java Reference
In-Depth Information
6.3.1
the
Collection
interface
The
Collection
interface represents a group of objects, known as its
elements
.
Some implementations, such as lists, are unsorted; others, such as sets and
maps, may be sorted. Some implementations allow duplicates; others do not.
Starting with Java 5, the
Collection
interface and the entire
Collection
s API
make use of generics. All containers support the following operations.
The
Collection
interface repre-
sents a group of
objects, known as
its
elements
.
boolean isEmpty( )
Returns
true
if the container contains no elements and
false
otherwise.
int size( )
Returns the number of elements in the container.
boolean add( AnyType x )
Adds item
x
to the container. Returns
true
if this operation succeeds and
false
otherwise (e.g., if the container does not allow duplicates and
x
is
already in the container).
boolean contains( Object x )
Returns
true
if
x
is in the container and
false
otherwise.
boolean remove( Object x )
Removes item
x
from the container. Returns
true
if
x
was removed and
false
otherwise.
void clear( )
Makes the container empty.
Object [ ] toArray( )
<OtherType> OtherType [ ] toArray ( OtherType [ ] arr )
Returns an array that contains references to all items in the container.
java.util.Iterator<AnyType> iterator( )
Returns an
Iterator
that can be used to begin traversing all locations in the
container.
Because
Collection
is generic, it allows objects of only a specific type
(
AnyType
) to be in the collection. Thus, the parameter to add is
AnyType
. The
parameter to
contains
and
remove
should be
AnyType
also; however, for back-
ward compatibility it is
Object
. Certainly, if
contains
or
remove
are called with
a parameter that is not of type
AnyType
, the return value will be
false
.
The method
toArray
returns an array that contains references to the items
that are in the collection. In some cases, it can be faster to manipulate this
array than to use an iterator to manipulate the collection; however, the cost of
Search WWH ::
Custom Search