|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
ACollectionrepresents a group of objects known as its elements. The
Collectioninterface is used to pass around collections of objects where maximum generality is desired. For example, by convention all general-purpose collection implementations have a constructor that takes aCollectionargument. This constructor, known as a conversion constructor, initializes the new collection to contain all the elements in the specified collection, whatever the given collection's subinterface or implementation type. In other words, it allows you to convert the collection's type.Suppose, for example, that you have a
Collection<String> c, which may be aList, aSet, or another kind ofCollection. This idiom creates a newArrayList(an implementation of theListinterface), initially containing all the elements inc.The following shows theList<String> list = new ArrayList<String>(c);Collectioninterface.The interface does about what you'd expect, given that apublic interface Collection<E> extends Iterable<E> { //Basic operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); //optional boolean remove(Object element); //optional Iterator iterator(); //Bulk operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); //optional boolean removeAll(Collection<?> c); //optional boolean retainAll(Collection<?> c); //optional void clear(); //optional //Array operations Object[] toArray(); <T> T[] toArray(T[] a); }Collectionrepresents a group of objects. The interface has methods to tell you how many elements are in the collection (size,isEmpty), to check whether 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 designed to remove a single instance of the specified element from theCollection, assuming that it contains the element to start with, and to returntrueif theCollectionwas modified as a result.
There are two ways to traverse collections: (1)with thefor-eachconstruct and (2) by usingIterators.for-each Construct
Thefor-eachconstruct allows you to concisely traverse a collection or array using aforloop see The for Statement. The following code uses the
for-eachconstruct to print out each element of a collection on a separate line.for (Object o : collection) System.out.println(o);Iterators
AnIteratoris an object that enables you to traverse through a collection and to remove elements from the collection selectively, if desired. You get an
Iteratorfor a collection by calling itsiteratormethod. The following is theIteratorinterface.Thepublic interface Iterator<E> { boolean hasNext(); E next(); void remove(); //optional }hasNextmethod returnstrueif the iteration has more elements, and thenextmethod returns the next element in the iteration. Theremovemethod removes the last element that was returned bynextfrom the underlyingCollection. Theremovemethod may be called only once per call tonextand throws an exception if this rule is violated.Note that
Iterator.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.Use
Iteratorinstead of thefor-eachconstruct when you need to:The following method shows you how to use an
- Remove the current element. The
for-eachconstruct hides the iterator, so you cannot callremove. Therefore, thefor-eachconstruct is not usable for filtering.- Replace elements in a list or array as you traverse it.
- Iterate over multiple collections in parallel.
Iteratorto filter an arbitraryCollection that is, traverse the collection removing specific elements.This simple piece of code is polymorphic, which means that it works for anystatic void filter(Collection> c) { for (Iterator> i = c.iterator(); i.hasNext(); ) if (!cond(i.next())) i.remove(); }Collectionregardless of implementation. This example demonstrates how easy it is to write a polymorphic algorithm using the Java Collections Framework.
Bulk operations perform an operation on an entireCollection. You could implement these shorthand operations using the basic operations, though in most cases such implementations would be less efficient. The following are the bulk operations:The
containsAll returnstrueif the targetCollectioncontains all the elements in the specifiedCollection.addAll adds all the elements in the specifiedCollectionto the targetCollection.removeAll removes from the targetCollectionall its elements that are also contained in the specifiedCollection.retainAll removes from the targetCollectionall its elements that are not also contained in the specifiedCollection. That is, 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 bulk operations, consider the following idiom to remove all instances of a specified element,
e, from aCollection,c.More specifically, suppose you want to remove all thec.removeAll(Collections.singleton(e));nullelements from aCollection.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. The array operations 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 that
cis aCollection. The following snippet dumps the contents ofcinto a newly allocated array ofObjectwhose length is identical to the number of elements inc.Suppose thatObject[] a = c.toArray();cis known to contain only strings (perhaps becausecis of typeCollection<String>). The following snippet dumps the contents ofcinto a newly allocated array ofStringwhose length is identical to the number of elements inc.String[] a = c.toArray(new String[0]);
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.