What is an Iterator interface?


The List and Set collections provide iterators, which are objects that allow going over all the elements of a collection in sequence. The java.util.Iterator<E> interface provides for one-way traversal andjava.util.ListIterator<E> provides two-way traversal. Iterator<E> is a replacement for the olderEnumeration 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, Set, or other data collection with iterators.

Iterator Methods
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 supportdelete. 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 as above but with enhanced Java 5 for loop

for (String s : alist) {
    System.out.println(s);
}

Example pre Java 5, with explicit iterator and downcasting

An iterator might be used as follows, wi.
ArrayList alist = new ArrayList(); // This holds type Object.
// . . . Add Strings to alist

for (Iterator it = alist.iterator(); it.hasNext(); ) {
    String s = (String)it.next();  // Downcasting is required pre Java 5.
    System.out.println(s);
}

People who read this post also read :



0 comments:

Post a Comment

Share

Twitter Delicious Facebook Digg Stumbleupon Favorites More