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
Iterator will give successive elements, but
Iterator is improved in such a way so the method names are shorter, and has an additional
Here is a side-by-side comparison:
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 !!
All of my websites are hosted on Bluehost. Why? Because they make it incredibly easy to get a new site up and running with their one-click automatic WordPress Blog installation.
You can use your Bluehost account to host multiple domains—no need to pay more for hosting when you’re ready to start another website.