Learnitweb

What’s the difference between Enumeration and Iterator interfaces ?

Difference between Enumeration and Iterator can be summarized with the help of following points:

  • Enumeration is a legacy interface used to traverse only the legacy classes like Vector and HashTable. Iterator is not a legacy interface. Iterator can be used for the traversal of collections like HashMap, LinkedList, ArrayList, HashSet, TreeMap, TreeSet etc.
  • Enumeration has read-only access to the elements in the collection. On the other side, Iterator can remove the elements from the collection.
  • Enumeration is not a universal cursor as it applies only to legacy classes. Iterator is a universal cursor as it is applicable for all the collection classes.
  • Enumeration was added to the jdk1.0 version while Iterator was added in jdk1.2 version.
  • 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.
  • Enumeration has methods hasMoreElements() and nextElement(). Iterator has methods hasNext(), next() and remove().

Both Iterator and Enumeration are available in java.util package. Both Iterator and Enumerations are unidirectional forward access cursor.
According to Java API Docs, Iterator is always preferred over the Enumeration.

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