5 Difference between Iterator and Enumeration with example : Java Collections Question


The most common interview question in Collections is What is the difference between iterator and enumeration.The main difference between Iterator and Enumeration is removal of the element while traversing the collection. Iterator can remove the element during traversal of collection as it has remove() method. Enumeration does not have remove() method. In this post I will share the difference and similarities between Iterator and Enumeration along with example.

Iterator

Iterator is the interface and found in the java.util package.
It has three methods

*hasNext()
*next()
*remove()

Read Also:   Java interview questions for experienced

Enumeration

Enumeration is also an interface and found in the java.util package .
It is used for passing through a collection, usually of unknown size.

It has following methods

*hasMoreElements()
*nextElement()

Note : Enumeration does not have remove() method.

Difference between Iterator and Enumeration

1. Remove() method :  The major difference between Iterator and Enumeration is that Iterator has the remove() method while Enumeration does not have remove() method.
Enumeration interface acts as a read only interface, one can not do any modifications to Collection while traversing the elements of the Collection. 
Iterator can do modifications (e.g using remove() method it removes the element from the Collection during traversal). 
  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Enumeration is used for read only access while Iterator is useful to manipulate the list.
2. Addition to JDK : Enumeration is added to the jdk1.0 version while Iterator is added in jdk1.2 version.

3. Fail-fast or Fail-safe : Enumeration is fail-safe in nature. It does not throw ConcurrentModificationException if Collection is modified during the traversal.
Iterator is fail-fast in nature. It throws ConcurrentModificationException if a Collection is modified while iterating other than its own remove() method. I have already shared the difference between fail-fast and fail-safe iterators in java.

4. Legacy :  Enumeration is a legacy interface which is used for traversing Vector, Hashtable. 
Iterator is not a legacy interface. Iterator can be used for the traversal of HashMap, LinkedList,  ArrayList, HashSet, TreeMap, TreeSet . 

5. Preference :  According to Oracle docs,

The functionality of Enumeration  is duplicated by the iterator interface.Iterator adds an optional remove operation,and has shorter method names. New implementations should consider using Iterator in preference to Enumeration. 

Similarities between Iterator and Enumeration in Java

1. Interface :Both Iterator and Enumeration are interfaces.

2. Package : Both Iterator and Enumeration are present in java.util package.
   

Example of Iterator and Enumeration

import java.util.*;
public class Performance {
    public static void main(String[] args){
        Vector v=new Vector();
        Object element;
        Enumeration enum;
        Iterator iter;
        long start;
        
        for(int i=0; i<1000000; i++){
            v.add("New Element");
        }
        
        enum=v.elements();
        iter=v.iterator();
        //*****CODE BLOCK FOR ITERATOR**********************
        start=System.currentTimeMillis();
        while(iter.hasNext()){
            element=iter.next();
        }
        System.out.println("Iterator took " + (System.currentTimeMillis()-start));
        //*************END OF ITERATOR BLOCK************************
        
        System.gc();   //request to GC to free up some memory
        //*************CODE BLOCK FOR ENUMERATION*******************
        start=System.currentTimeMillis();
        while(enum.hasMoreElements()){
            element=enum.nextElement();
        }
        System.out.println("Enumeration took " + (System.currentTimeMillis()-start));
        //************END OF ENUMERATION BLOCK**********************
    }
}



Recap : Difference between Iterator and Enumeration in Java



Iterator         Enumeration
Throw ConcurrentModification ExceptionYes                No
Remove() methodYes, you can remove the element
while traversing it
                No
Addition to JDK1.2               1.0
LegacyNo               Yes



Quesiton : Why we need Enumeration  instead of  for(int i=0; i< v.size();i++){} loop?

For loops are expensive to the processor when the collection reaches large sizes, as many operations are done just to compute the first line:

For loop total operations :
  • int i = 0 is an assignment and creation (2 operations)
    i get size, check value of i, and compare (3 operations)
    i++ gets i then adds 1 to it [++i is only 2 operations] this one (3 operations)
    *7/8 operations in total, each time the loop runs through
Enumeration total operations :
  • where an enumeration or iterator uses a while(){}
    while(v.hasNext()) has next true or false (1 operation)
    while(v.hasMoreElements()) has more true or false (1 operation)
    *Only one operation per repeat of this loop


About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry