Enumeration vs Iterator


After practicing Enumeration and Iterator with examples, let us summarize the differences. Both Enumeration and Iterator are used for iterating elements of a data structure. Iterator, being latest, comes with more features tabulated below.

Enumeration Iterator
Introduced with JDK 1.0 Introduced with JDK 1.2
Cannot remove any elements Can remove elements from the original DS itself
Methods are hasMoreElements() and nextElement() Methods are hasNext() and next()
Methods are difficult to remember Methods are easy to remember

Both nextElement() and next() return an object of Object class. Both iterate in forward direction only (remember, ListIterator can move backwards also).

Example on Enumeration of Enumeration vs Iterator
import java.util.*;
public class EnumerationIteration
{
  public static void main(String args[])
  {
    Vector coffeeShops = new Vector();
    coffeeShops.add("Chipotele"); coffeeShops.add("Starbucks"); coffeeShops.add("Dunkin Donuts");

    System.out.println("USA Coffee shops:");
    Enumeration e = coffeeShops.elements();
    while(e.hasMoreElements())
    {
      System.out.println(e.nextElement());
    }
  }
}


ss
Output screen on Enumeration vs Iterator

Another example with explanation is available at Enumeration Interface.

Example on Iterator of Enumeration vs Iterator
import java.util.*;
public class EnumerationIteration
{
  public static void main(String args[])
  {
    Vector foodChain = new Vector();
    foodChain.add("Mc Donalds"); foodChain.add("Subway"); foodChain.add("Chipotele");

    System.out.println("USA Food shops:");
    Iterator it = foodChain.iterator();
    while(it.hasNext())
    {
      System.out.println(it.next());
    }
  }
}


ss
Output screen on Enumeration vs Iterator

Another example with explanation is available at Iterator Interface.

3 thoughts on “Enumeration vs Iterator”

Leave a Comment

Your email address will not be published.