The List and Set collections provide iterators, which are objects that allow
going over all the elements of a collection. The java.util.Iterator
interface provides for one-way traversal and java.util.ListIterator
provides two-way traversal. Iterator is a replacement for the
Enumeration class which was used before collections were added
to Java.
Iterators are created by calling the iterator() or listIterator() method of a List or Set.
Iterator defines three methods, one of which is optional.
| Result | Method | Description |
|---|---|---|
b = | it.hasNext() |
true if there are more elements for the iterator. |
obj = | it.next() |
Returns the next object. If a generic list is being accessed, the iterator
will return something of the list's type. Pre-generic Java iterators always returned type
Object, so a downcast was usually required. |
| it.remove() |
Removes the most recent element that was returned by next.
Not all collections support delete.
An UnsupportedOperationException will be thrown if the collection
does not support remove(). |
An iterator might be used as follows.
ArrayList<String> alist = new ArrayList<String>();
// . . . Add Strings to alist
for (Iterator<String> it = alist.iterator(); it.hasNext(); ) {
String s = it.next(); // No downcasting required.
System.out.println(s);
}
An iterator might be used as follows.
ArrayList alist = new ArrayList(); // . . . Add Strings to alist for (Iterator it = alist.iterator(); it.hasNext();