Difference between Enumeration and Iterator interface in Java

In this post, we will discuss the difference between Enumeration and Iterator interface in Java.


 

Both Iterator and Enumeration are used to retrieve the elements from the Collections in Java. The Iterator interface was introduced in JDK 1.2, whereas Enumeration interface was there from the beginning. This post provides an overview of the difference between Enumeration and Iterator interface in Java –

  1. Enumeration is a legacy interface and Iterator should be preferred in preference to Enumeration. This is because the Iterator officially took place of Enumeration in the Java collections framework.
     
  2. Enumeration interface is used by Vector, HashTable and Stack classes, which are themselves obsolete, whereas Iterators are used to traverse almost every class in the Java Collection Framework.
     
  3. Iterators allow the caller to remove elements from the underlying collection during the iteration using iterator’s own remove() method. Since this method is not defined for Enumeration, we cannot structurally modify a list during iteration.
     
  4. Enumeration is fail-safe in nature while an Iterator is fail-fast in nature.
     
  5. Enumeration in Java moves only in forward direction. There is another special type of Iterator, called ListIterator, which facilitates bi-directional access.
     
  6. The Iterator has shorter method names – hasMore() and next(), as opposed to hasMoreElements() and nextElement() of Enumeration interface.

 
References: Enumeration Javadoc

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of