What is the Difference between Enumeration and Iterator
Points To Remember
  • In java 1.0, there were two primary collection classes HashMap and Vector.
  • Enumeration was a class in Java 1.0 to Iterate through these collection classes.(They are not the enum types.)
  • Iterator was introduced in Java 1.2

Difference between Enumeration and Iterator.
It was introduces in Java v1.0It was introduced in java v1.2
Enumeration does not have remove() methodIterator has remove() method
Enumeration provides a read only iteration over collectionIterator provides iteration over collections along with manipulation of objects like adding and removing from object.
Enumeration is less safe and secureIterator is more secure and safe, when multiple thread work on same object, it does not allow any thread to modify the object and throws ConcurrentModificationException.
Enumeration has lengthy method names like
  • hasMoreElements()
  • nextElements()
Iterator have short method names like
  • hasNext()
  • next()
Enumeration is used when we want to iterate Collection object in read only manner.Iterator is used when we want to iterate on collection object along with object manipulation.

Using Enumeration to Iterate.
Vector names = new Vector();

// ... add some names to the collection

Enumeration e = names.elements();
while (e.hasMoreElements())
    String name = (String) e.nextElement();
Using Iterator to Iterate.
List names = new LinkedList();

// ... add some names to the collection

Iterator i = names.iterator();
while (i.hasNext())
    String name = (String) i.next();

No comments :

Post a Comment