Difference between Enumerator
and Iterator
can be asked to you in any java interview. In this post, I am listing down a few differences which you may cite while answering the question.
1. Enumeration
The Enumeration helps to enumerate through the elements of a vector, the keys of a hashtable, and the values in a hashtable. The successive calls to the nextElement()
method returns successive elements of the collection.
Using Enumeration is not recommended anymore.
Vector<String> vector = new Vector<>();
vector.add("A");
vector.add("B");
vector.add("C");
while (vector.hasMoreElements()) {
System.out.println(vector.nextElement());
}
2. Iterator
Iterator is the recommended way to iterate over collections since Java 1.2 and takes place of Enumeration. Note that An Enumeration
can be converted into an Iterator
by using the Enumeration.asIterator()
method.
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
Iterator<String> itr = list.iterator();
while(itr.hasNext()){
System.out.println(it.next());
}
3. Difference between Enumeration and Iterator
First of all, enumerations are only applicable for legacy classes e.g Hashtable, and Vector. Enumerations were part of the initial java release JDK1.0. While iterators were included in JDK 1.2 along with the Collections framework which was also added in JDK 1.2 only.
So clearly, Iterators were designed as totally focused on the collection framework only. If you read the Iterator’s java documentation, it clearly states its 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.
Iterator 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:
Enumeration | Iterator |
---|---|
hasMoreElement() | hasNext() |
nextElement() | next() |
N/A | remove() |
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 !!