2017  Kodetalk | Feedback | Privacy Policy | Terms | About

Difference between Java Enumeration and Iterator

What is the exact difference between these two interfaces? Does Enumeration have benefits over using Iterator? If anyone could elaborate, a reference article would be appreciated.

According to Java API Specification for the Iterator interface, there is an explanation of the differences between Enumeration:

Iterators differ from enumerations in two ways:

  • Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  • Method names have been improved.

The bottom line is, both Enumeration and Iterator will give successive elements, but Iterator is improved in such a way so the method names are shorter, and has an additional remove method. Here is a side-by-side comparison:

Enumeration                     Iterator
  ----------------                ----------------
  hasMoreElement()            hasNext()
  nextElement()                   next()
  N/A                                   remove()

As also mentioned in the Java API Specifications, for newer programs, Iterator should be preferred over Enumeration, as "Iterator takes the place of Enumeration in the Java collections framework." (From the Iterator specifications.)

Iterators are fail-fast . i.e. when one thread changes the collection by add / remove operations , while another thread is traversing it through an Iterator using hasNext() or next() method, the iterator fails quickly by throwing ConcurrentModificationException . The fail-fast behavior of iterators can be used only to detect bugs. The Enumerations returned by the methods of classes like Hashtable, Vector are not fail-fast that is achieved by synchronizing the block of code inside the nextElement() method that locks the current Vector object which costs lots of time.
Answer is