Difference between enumerator and iterator?

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:

  1. Iterators allow the caller to remove elements from the underlying collection during the iteration with well-defined semantics.
  2. 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]

EnumerationIterator
hasMoreElement()hasNext()
nextElement()next()
N/Aremove()

[/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 !!

Was this post helpful?

Join 8000+ Awesome Developers, Like YOU!

Leave a Comment

About HowToDoInJava

This blog provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions, and frequently asked interview questions.