Difference between Java Enumeration and Iterator
Solution 1:
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.)
Solution 2:
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.
Solution 3:
"Officially", they are supposed to be similar with the iterator interface supporting extra operations (e.g., removal). Generally, the tendency is to use iterators.
Here is from the enumeration interface javadocs:
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.