|
|
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 the
Collectioninterface 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 ofCollectionlikeSetorList) have a constructor that takes aCollectionargument. This constructor initializes the newCollectionto contain all of the elements in the specifiedCollection. This constructor allows the caller to create aCollectionof 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 theListinterface), initially containing all of the elements inc:List l = new ArrayList(c);The
Collectioninterface 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[]); }Collectionrepresents 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
addmethod is defined generally enough so that it makes sense for collections that allow duplicates as well as those that don't. It guarantees that theCollectionwill contain the specified element after the call completes, and returnstrueif theCollectionchanges as a result of the call. Similarly, theremovemethod is defined to remove a single instance of the specified element from theCollection, assuming theCollectioncontains the element, and to returntrueif theCollectionwas modified as a result.
The object returned by theiteratormethod 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
Iteratorallows 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
Iteratorinterface is shown below:Thepublic interface Iterator { boolean hasNext(); Object next(); void remove(); // Optional }hasNextmethod is identical in function toEnumeration.hasMoreElements, and thenextmethod is identical in function toEnumeration.nextElement. Theremovemethod removes from the underlyingCollectionthe last element that was returned bynext. Theremovemethod may be called only once per call tonext, and throws an exception if this condition is violated. Note thatIterator.removeis 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
Iteratorto 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
Collectionthat 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
Enumerationinstead 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 entireCollectionin 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: Returnstrueif the targetCollectioncontains all of the elements in the specifiedCollection(c).addAll: Adds all of the elements in the specifiedCollectionto the targetCollection.removeAll: Removes from the targetCollectionall of its elements that are also contained in the specifiedCollection.retainAll: Removes from the targetCollectionall of its elements that are not also contained in the specifiedCollection. That is to say, it retains only those elements in the targetCollectionthat are also contained in the specifiedCollection.clear: Removes all elements from theCollection.addAll,removeAll, andretainAllmethods all returntrueif the targetCollectionwas 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,
efrom 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 immutableSetcontaining only the specified element.
ThetoArraymethods are provided as a bridge between collections and older APIs that expect arrays on input. They allow the contents of aCollectionto 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
cis aCollectionThe following snippet dumps the contents ofcinto a newly allocated array ofObjectwhose length is identical to the number of elements inc:SupposeObject[] a = c.toArray();cis known to contain only strings. The following snippet dumps the contents ofcinto a newly allocated array ofStringwhose 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-2004 Sun Microsystems, Inc. All rights reserved.