Enumeration VS Iterator in Java

Connect with

Oracle Java
It’s very important to understand the fundamental of both the interface for interview point of view or for work assignment aspect. Where should you use which interface? you can say most of the time you get encountered this question in interview which one should be used where?

Both of the interface used to traverse the added Element from the collection during traversal in java. you know , both the interface is the key interface in java. As you know, Enumeration is read-only, so it does not allow you to remove Element from collection, in fact you can say, not remove() method in Enumeration interface.

Let us try to understand each of them one by one and then move to similarity and differences between them.

Enumeration

Enumeration is older interface since jdk 1.0 , which is being used to traverse the item added in the collection. Enumeration does not allow you to remove item added in the collection, as this is read-only. Key methods are:
hasMoreElement() ,
nextElement()

Iterator

Iterator interface is added later , you can say , this is improved version of Enumeration. Whenever you required to remove item from collection while iterating you can use this interface. this is more safe and secure than Enumeration. Iterator allow you to remove element from collection . Key methods:
hasNext() : this returns true if item present in the next cursor position.
next() : it returns Element added in next cursor position.

Enumeration VS Iterator

  • Enumeration is older since JDK 1.0 and Iterator introduced in JDK later.
  • functionality of Iterator is duplicated from Enumeration.
  • Iterator is more secure and safe compared to Enumeration, because of thread safe, it means, Iterator does not allow
  • remove() method has been added in Iterator to make it immutable it means Enumeration i read-only.
  • name of method in Iterator is shorter than Enumeration. e.g. Iterator methods: hasnext() next() remove() while name of Enumeration interface: hasMoreElement(), nextElement()
  • Enumeration can be used whenever you want Read-only

Usage of Enumeration and Iterator

This is very important which one should be used where, this is the gist of the topic. There are two different aspect. first, as you know Iterator is improved version of Enumeration, so you should use Iterator always. second, Enumeration is read-only, so when you simply iteration is required not removal of item, then Enumeration should be used.

Suggestions are welcome, to improve this topic, please write comment by sharing your thought.


Connect with

Leave a Reply

Your email address will not be published. Required fields are marked *