Difference between Enumerator
and Iterator
can be asked to you in any java interview. In this post, I am listing down few differences which you may cite while answering the question.
Difference between enumerator and iterator
First of all, enumerations are only applicable for legacy classes e.g Hashtable, Vector. Enumerations were part of initial java release JDK1.0. While, iterators were included in JDK 1.2 along with Collections framework which was also added in JDK 1.2 only.
So clearly, Iterators were designed as totally focused on collection framework only. If you read the Iterator’s java documentation, it clearly states it’s purpose. Quoting from oracle’s official website:
An iterator over a collection. Iterator takes the place of Enumeration in the Java Collections Framework. 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.
This interface is a member of the Java Collections Framework.
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:
[su_table]
Enumeration | Iterator |
---|---|
hasMoreElement() | hasNext() |
nextElement() | next() |
N/A | remove() |
[/su_table]
Java API Specifications recommend, for newer programs, Iterator should be preferred over Enumeration, as “Iterator takes the place of Enumeration in the Java collections framework.”
That’s all for this simple yet important topic.
Happy Learning !!
Ask Questions & Share Feedback