Iterator Interface
Home ] Up ] Collection Interface ] List Interface ] [ Iterator Interface ] ListIterator Interface ] ArrayList/Iterator Example ] LinkedList Example ] Stack Class ]

 

 

The Iterator interface is designed to provide the interface for a class that can iterate through a collection.  It is designed to replace the Enumeration interface

Collection
    List
    Set
        SortedSet
Comparable (in java.lang package)
Comparator
Enumeration
Iterator
    ListIterator
Map
    SortedMap

The Iterator interface defines the following methods:

package java.util;

public interface Iterator 
{
    /**
     * Returns true if the iteration has more elements. (In other
     * words, returns true if next would return an element
     * rather than throwing an exception.)
     *
     * @return true if the iterator has more elements.
     */
    boolean hasNext();

    /**
     * Returns the next element in the iteration.
     *
     * @returns the next element in the iteration.
     * @exception NoSuchElementException iteration has no more elements.
     */
    Object next();

    /**
     * 
     * Removes from the underlying collection the last element returned by the
     * iterator (optional operation).  This method can be called only once per
     * call to next.  The behavior of an iterator is unspecified if
     * the underlying collection is modified while the iteration is in
     * progress in any way other than by calling this method.
     *
     * @exception UnsupportedOperationException if the remove
     *		  operation is not supported by this Iterator.
     
     * @exception IllegalStateException if the next method has not
     *		  yet been called, or the remove method has already
     *		  been called after the last call to the next
     *		  method.
     */
    void remove();
}

Note that it is reminiscent of Enumeration, but with two differences:

  • Method names have changed:
    • hasMoreElements() becomes hasNext()
    • nextElement() becomes next()
  • Iterator allows the caller to remove elements from an underlying collection during the iteration, with well-defined semantics.  (Enumeration does not support this.)
 

This page was last modified on 02 October, 2007