Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
A Collectionrepresents a group of objects, known as its elements. The primary use of theCollection
interface is to pass around collections of objects where maximum generality is desired. For example, by convention all general-purpose collection implementations (which typically implement some subinterface ofCollection
likeSet
orList
) have a constructor that takes aCollection
argument. This constructor initializes the newCollection
to contain all of the elements in the specifiedCollection
. This constructor allows the caller to create aCollection
of a desired implementation type, initially containing all of the elements in any givenCollection
, whatever its subinterface or implementation type. Suppose you have aCollection
,c
, which may be aList
, aSet
, or some other kind ofCollection
. The following one-liner creates a newArrayList
(an implementation of theList
interface), initially containing all of the elements inc
:List l = new ArrayList(c);The
Collection
interface is shown below:The interface does about what you'd expect, given that apublic interface Collection { // Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(Object element); // Optional boolean remove(Object element); // Optional Iterator iterator(); // Bulk Operations boolean containsAll(Collection c); boolean addAll(Collection c); // Optional boolean removeAll(Collection c); // Optional boolean retainAll(Collection c); // Optional void clear(); // Optional // Array Operations Object[] toArray(); Object[] toArray(Object a[]); }Collection
represents a group of objects. It has methods to tell you how many elements are in the collection (size
,isEmpty
), to check if a given object is in the collection (contains
), to add and remove an element from the collection (add
,remove
), and to provide an iterator over the collection (iterator
).The
add
method is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't. It guarantees that theCollection
will contain the specified element after the call completes, and returnstrue
if theCollection
changes as a result of the call. Similarly, theremove
method is defined to remove a single instance of the specified element from theCollection
, assuming theCollection
contains the element, and to returntrue
if theCollection
was modified as a result.
The object returned by theiterator
method deserves special mention. It is an Iterator, which is very similar to an Enumeration, but differs in two respects:The first point is important: There was no safe way to remove elements from a collection while traversing it with an
Iterator
allows the caller to remove elements from the underlying collection during the iteration with well-defined semantics.- Method names have been improved.
Enumeration
. The semantics of this operation were ill-defined, and differed from implementation to implementation.The
Iterator
interface is shown below:Thepublic interface Iterator { boolean hasNext(); Object next(); void remove(); // Optional }hasNext
method is identical in function toEnumeration.hasMoreElements
, and thenext
method is identical in function toEnumeration.nextElement
. Theremove
method removes from the underlyingCollection
the last element that was returned bynext
. Theremove
method may be called only once per call tonext
, and throws an exception if this condition is violated. Note thatIterator.remove
is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress.The following snippet shows you how to use an
Iterator
to filter aCollection
, that is, to traverse the collection, removing every element that does not satisfy some condition:Two things should be kept in mind when looking at this simple piece of code:static void filter(Collection c) { for (Iterator i = c.iterator(); i.hasNext(); ) if (!cond(i.next())) i.remove(); }
- The code is polymorphic: it works for any
Collection
that supports element removal, regardless of implementation. That's how easy it is to write a polymorphic algorithm under the collections framework!- It would have been impossible to write this using
Enumeration
instead ofIterator
, because there's no safe way to remove an element from a collection while traversing it with anEnumeration
.
The bulk operations perform some operation on an entireCollection
in a single shot. They are shorthands in the sense that each of them can be simulated, perhaps less efficiently, using the operations described above.The
containsAll
: Returnstrue
if the targetCollection
contains all of the elements in the specifiedCollection
(c
).addAll
: Adds all of the elements in the specifiedCollection
to the targetCollection
.removeAll
: Removes from the targetCollection
all of its elements that are also contained in the specifiedCollection
.retainAll
: Removes from the targetCollection
all of its elements that are not also contained in the specifiedCollection
. That is to say, it retains only those elements in the targetCollection
that are also contained in the specifiedCollection
.clear
: Removes all elements from theCollection
.addAll
,removeAll
, andretainAll
methods all returntrue
if the targetCollection
was modified in the process of executing the operation.As a simple example of the power of the bulk operations, consider following idiom to remove all instances of a specified element,
e
from aCollection
,c
.:More specifically, suppose that you want to remove all of the null elements from ac.removeAll(Collections.singleton(e));Collection
:This idiom usesc.removeAll(Collections.singleton(null));Collections.singleton
, which is a static factory method that returns an immutableSet
containing only the specified element.
ThetoArray
methods are provided as a bridge between collections and older APIs that expect arrays on input. They allow the contents of aCollection
to be translated into an array. The simple form with no arguments creates a new array ofObject
. The more complex form allows the caller to provide an array or to choose the runtime type of the output array.For example, suppose
c
is aCollection
The following snippet dumps the contents ofc
into a newly allocated array ofObject
whose length is identical to the number of elements inc
:SupposeObject[] a = c.toArray();c
is known to contain only strings. The following snippet dumps the contents ofc
into a newly allocated array ofString
whose length is identical to the number of elements inc
:String[] a = (String[]) c.toArray(new String[0]);
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2001 Sun Microsystems, Inc. All rights reserved.