Ask Questions?

View Latest Questions


 
 

Iterators
Posted on: July 26, 2006 at 12:00 AM
Iterator is a replacement for the Enumeration class which was used before collections were added to Java.

Java Notes

Iterators

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.

Creating an Iterator

Iterators are created by calling the iterator() or listIterator() method of a List or Set.

Iterator Methods

Iterator defines three methods, one of which is optional.

ResultMethod 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().

Example with Java 5 generics

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);
}

Example Pre Java 5

An iterator might be used as follows.

ArrayList alist = new ArrayList();
// . . . Add Strings to alist

for (Iterator it = alist.iterator(); it.hasNext();