Difference between Java Enumeration and Iterator
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.
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.)