Java – 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.

Best Solution

Looking at the 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 improved the method names by shortening away the verbiage, and it has an additional remove method. Here is a side-by-side comparison:

  Enumeration                     Iterator
  ----------------                ----------------
  hasMoreElements()               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.)