Iterator in Java

In Java, Iterator is an interface available in Collection framework in java.util package. It is a Java Cursor used to iterate a collection of objects. They are used in Java to retrieve elements one by one. They must be used whenever we want to enumerate elements in all Collection framework implemented interfaces like Set, List, Queue, Deque and also in all implemented classes of Map interface.

  • It is used to traverse a collection object elements one by one
  • It is available since Java 1.2 Collection Framework
  • It is applicable for all Collection classes. So it is also known as Universal Java Cursor
  • It supports both READ and REMOVE Operations
  • Compare to Enumeration interface, Iterator method names are simple and easy to use

Iterator interface defines three methods

  • boolean hasNext()
    • Returns true if  the iteration has more elements
  • E next()
    • Returns the next element in the iteration
    • It throws NoSuchElementException if no more elements are present
  • void remove()
    • Remove the next element in the iteration
    • Throws two exceptions
      • UnsupportedOperationException
      • IllegalStateException

Limitations of Iterator

  • Only forward direction iterating is possible
  • Replacement and addition of new element is not supported by it

ListIterator

  • It has the capability to traverse the list in both direction
  • This interface also provide the facility to insert the element in a list that means we can perform removal as well as insertion
  • Since List is ordered and it is indexed so we can travel it forward direction as well as backward direction
  • Set is unordered that is why the listIterator() method is available only for List interface not for Set

Methods Declared by ListIterator

  • void add(Object obj)
    • Inserts obj into the list in front of the element that will be returned by the next call to next( )
  • boolean hasNext( )
    • Returns true if there is a next element
  • boolean hasPrevious( )
    • Returns true if there is a previous element
  • Object next( )
    • Returns the next element
  • int nextIndex( )
    • Returns the index of the next element. If there is no next element, returns the size of the list
  • Object previous( )
    • Returns the previous element
  • int previousIndex( )
    • Returns the index of the previous element. If there is not a previous element, returns -1
  • void remove( )
    • Removes the current element from the list
  • void set(Object obj)
    • Assigns obj to the current element. This is the element last returned by a call to either next( ) or previous( )

 

Example explaining implementation of Iterator

import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Iterator;

public class Difference {
     public static void main(String args[])
    {
        ArrayList al=new ArrayList();
        al.add("one");
        al.add("two");
        al.add("three");

        /*ListIterator*/
        ListIterator itr=al.listIterator();
        while(itr.hasNext())            // start from 0th position and goes one by one till the end
        {
            System.out.println(itr.next());
        }
        System.out.println("\nend\n");
        while(itr.hasPrevious())        // start from last position and goes one by one to the beginning
        {
            System.out.println(itr.previous());
        }

        /*Iterator*/
        Iterator itr1=al.iterator();
        while(itr1.hasNext())
        {
            System.out.println(itr1.next());
        }
        /*There is no hasPrevious() and previous methods in Iterator*/
    }
}
/*
 * ListIterator can move in forward as well as in backword direction..
 * but Iterator can move only in forward direction
 */

OUTPUT:
difference between iterator and listiterator

%d bloggers like this: