Way2Java

Java Iterator Interface Example

Java Iterator Interface Example: JDK 1.0 Enumeration is replaced by Iterator interface in JDK 1.2. Being latest, it comes with many advantages over Enumeration. Like Enumeration, Java Iterator interface is also used for iterating the elements.
Java Iterator Interface Example
import java.util.*;
public class IteratorDemo
{
  public static void main(String args[])
  {
    Vector vect1 = new Vector();
    vect1.addElement("Raju");  
    vect1.addElement("Reddy");
    vect1.addElement("Rao");
    vect1.addElement("Ratnakar");

    Iterator it = vect1.iterator();

    while(it.hasNext())
    {
      Object obj1 = it.next();
      System.out.print(obj1 + " ");
    }
  }
}

The above program just looks like Enumeration only, but replaced by Iterator. The methods are hasNext() in place of hasMoreElements(). And also next() in place of nextElement(). These two new methods, designers felt more appropriate to remember easily.

Java Iterator over Java Enumeration

Let us see where Iterator takes a lead over Enumeration. With Iterator, we can remove an element from the vector. Removing with Iterator, removes in the original Vector itself. This facility does not exist with Enumeration. Enumeration is useful to just print the elements.

Java Iterator interface comes with the following methods.

1. public abstract boolean hasNext();
2. public abstract Object next();
3. public abstract void remove();

Let us rewrite the above code where elements Raju and Rao are removed. After removing, the vector elements are again read and printed to check whether removal is really affected or not. Following Java Iterator Interface Example uses the above methods.

import java.util.*;
public class IteratorDemo
{
  public static void main(String args[])
  {
    Vector vect1 = new Vector();
    vect1.addElement("Raju");  
    vect1.addElement("Reddy");
    vect1.addElement("Rao");
    vect1.addElement("Ratnakar");

    Iterator it1 = vect1.iterator();
    System.out.print("Before removal elements: ");		
    while(it1.hasNext())
    {
      Object obj1 = it1.next();
      System.out.print(obj1 + " ");
    }
           // after printing, now let us remove the Raju and Rao
    Iterator it2 = vect1.iterator();
    while(it2.hasNext())
    {
      Object obj2 = it2.next();
      if(obj2.equals("Raju") || obj2.equals("Rao"))
      {
        it2.remove();  
      }
   }
   System.out.print("\nElements after removal: ");
           // create a new Iterator object with new elements
   Iterator it3 = vect1.iterator();
   while(it3.hasNext())
   {
     Object obj3 = it3.next();
     System.out.print(obj3 + " ");
   }
 }
}

        if(obj2.equals("Raju") || obj2.equals("Rao"))
        {
          it2.remove();  
        }

The remove method of Iterator removes Raju and Rao. It is proved when the elements are printed again with it3.

The Iterator comes with a sub interface "ListIterator". ListIterator comes with some more advantages over Iterator.