An iterator is an object that points at elements in a collection. An iterator divides the collection into the elements it has "seen" and the elements that it has not seen. An iterator points at the next unseen element:
The Java Collections Framework includes the Iterator interface:
interface Iterator<T> {
boolean hasNext(); // = true if more
unseen elements
T next(); // = see next unseen element
void remove(); // removes last seen element
}
Here's a typical example of iterating through a collection:
Collection<String> book = new TreeSet<String>();
book.add("This");
book.add("is");
book.add("the");
book.add("end");
// etc.
Iterator<String> p = book.iterator();
while(p.hasNext()) {
String word = p.next();
System.out.println(word);
}
Here's the output produced. Notice that the order of elements has changed:
This
end
is
the
Be careful, iterators can become obsolete. The following code:
p = book.iterator();
Iterator q = book.iterator();
p.next();
p.remove();
System.out.println(q.next());
produces the error:
Exception in thread "main" java.util.ConcurrentModificationException
For this reason Java iterators are sometimes called fail-fast iterators.
Starting in Java 5.0 iterators became anachronistic. The cool way to iterate through a collection is to use the enhanced for loop:
for(TYPE VARIABLE: COLLECTION) STATEMENT
For example the iteration:
Iterator<String> p = book.iterator();
while(p.hasNext()) {
String word = p.next();
System.out.println(word);
}
can be replaced by:
for(String word: book) {
System.out.println(word);
}