Iterator Interface in Java


  • An iterator is an object that is used with a collection to provide sequential access to the collection elements.This access allows examination and possible modification of the elements
  • An iterator imposes an ordering on the elements of a collection even if the collection itself does not impose any order on the elements it contains
    • If the collection does impose an ordering on its elements, then the iterator will use the same ordering
  • Java provides an Iterator<T> interface.Any object of any class that satisfies the Iterator<T> interface is an Iterator<T> 
  • An Iterator<T> does not stand on its own.It must be associated with some collection object using the method iterator
    • If c is an instance of a collection class (e.g., HashSet<String>), the following obtains an iterator for c:                                                     Iterator iteratorForC = c.iterator();
  • The Iterator interface specifies 3 methods:
    • boolean hasNext(): returns true if this iteration has more elements
    • next(): returns the next element in this iteration
    • void remove() : Removes from the underlying collection the last element returned by the iterator.

Search: