| ★ wanayoo — archive 1999 http://developer.java.sun.com/developer/Books/corejava/page2.html | Nouvelle recherche | Portail wanayoo |
|
|
|
Book Excerpt Index
Core Java 2, Volume IIby Cay S. Horstmann and Gary CornellChapter 2: CollectionsCollection and Iterator Interfaces in the Java Library
The fundamental interface for collection classes in the Java library is the
boolean add(Object obj) Iterator iterator()There are several methods in addition to these two; we will discuss them later. The add method adds an object to the collection. The add
method returns true if
adding the object actually changed the collection; false, if the collection is
unchanged. For example, if you try to add an object to a set and the object
is already present, then the add request is rejected since sets reject
duplicates.
The
The Object next() boolean hasNext() void remove()By repeatedly calling the next method, you can visit the elements
from the
collection one by one. However, if you reach the end of the collection, the
next method throws a NoSuchElementException. Therefore, you need
to call the hasNext method before calling next. That method
returns true if the iterator object still has more elements to
visit. If you want to inspect all elements in a container, you request an
iterator and then keep calling the next method while
hasNext returns true.
Iterator iter = c.iterator();
while (iter.hasNext())
{ Object obj = iter.next();
do something with obj
}
NOTE: Old-timers will notice that the next and hasNext methods of
the
Iterator interface serve the same purpose as the nextElement and
hasMoreElements methods of an Enumeration. The designers of the Java
collection library could have chosen to extend the Enumeration interface.
But they disliked the cumbersome method names and chose to introduce a new
interface with shorter method names instead.
Finally, the
You may well wonder why the remove method is a part of the
There is an important conceptual difference between iterators in the Java
collection library and iterators in other libraries. In traditional collection
libraries such as the Standard Template Library of C++, iterators are modeled
after array indexes. Given such an iterator, you can look up the element that
is stored at that position, much like you can look up an array element
Instead, you should think of Java iterators as being between elements. When
you call
NOTE: Here is another useful analogy. You can think of Iterator.next
as the
equivalent of InputStream.read. Reading a byte from a stream
automatically
consumes the byte. The next call to read consumes and returns
the next byte
from the input. Similarly, repeated calls to next let you read all elements
in a collection.
You must be careful when using the
Iterator it = c.iterator();
it.next(); // skip over the
//first element
it.remove(); // now remove it
More importantly, there is a dependency between calls to the next
and remove
methods. It is illegal to call remove if it wasn't preceded by a call to next.
If you try, an IllegalStateException is thrown.
If you want to remove two adjacent elements, you cannot simply call it.remove(); it.remove(); // Error!Instead, you must first call next to jump over the element to be removed.
it.remove(); it.next(); it.remove(); // OkBecause the collection and iterator interfaces are generic, you can write utility methods that operate on any kind of collection. For example, here is a generic print method that prints all elements in a collection.
public static void print(Collection c)
{ System.out.print("[ ");
Iterator iter = c.iterator();
while (iter.hasNext())
System.out.print(
iter.next() + " ");
System.out.println("]");
}
NOTE: We give this example to illustrate how to write a generic method. If you want to print the elements in a collection, you can just call System.out.println(c). This works because each collection class
has a
toString method that returns a string containing all elements
in the collection.
Here is a method that adds all objects from one collection to another:
public static boolean addAll(
Collection to, Collection from)
{ Iterator iter = from.iterator();
boolean modified = false;
while (iter.hasNext())
if (to.add(iter.next()))
modified = true;
return modified;
}
Recall that the add method returns true if adding
the element modified the
collection. You can implement these utility methods for arbitrary collections
because the Collection and Iterator interfaces supply fundamental methods such
as add and next.
The designers of the Java library decided that some of these utility methods
are so useful that the library should make them available. That way, users
don't have to keep reinventing the wheel. The
Had int size() boolean isEmpty() boolean contains(Object obj) boolean containsAll(Collection c) boolean equals(Object other) boolean addAll(Collection from) boolean remove(Object obj) boolean removeAll(Collection c) void clear() boolean retainAll(Collection c) Object[] toArray()Many of these methods are self-explanatory; you will find full documentation in the API notes at the end of this section.
Of course, it is a bother if every class that implements the
public class AbstractCollection
implements Collection
{ . . .
public abstract boolean add(
Object obj);
public boolean addAll(
Collection from)
{ Iterator iter = iterator();
boolean modified = false;
while (iter.hasNext())
if (add(iter.next()))
modified = true;
return modified
}
. . .
}
A concrete collection class can now extend the AbstractCollection class.
It is now up to the concrete collection class to supply an add method, but
the This is a good design for a class framework. The users of the collection classes have a richer set of methods available in the generic interface, but the implementors of the actual data structures do not have the burden of implementing all the routine methods.
java.util.Iterator
|