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 –
- 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.
- 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.
- 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.
- Enumeration is fail-safe in nature while an Iterator is fail-fast in nature.
- Enumeration in Java moves only in forward direction. There is another special type of Iterator, called ListIterator, which facilitates bi-directional access.
- The Iterator has shorter method names – hasMore() and next(), as opposed to hasMoreElements() and nextElement() of Enumeration interface.
References: Enumeration Javadoc
Thanks for reading.