What is the Difference Between Enumeration and Iterator?

🆚 Go to Comparative Table 🆚

Enumeration and Iterator are both interfaces in Java used to traverse and access elements from a Collection object. However, they have some differences:

  1. Modifications: Enumeration acts as a read-only interface, meaning you cannot make any modifications to the Collection while traversing its elements. On the other hand, Iterator allows you to perform modifications, such as adding and removing elements during iteration.
  2. remove() method: Enumeration does not have a remove() method, while Iterator does. This allows you to remove elements from the underlying collection while iterating through it.
  3. Applicability: Enumeration is only applicable to legacy classes like Vector and Hashtable, while Iterator can be used with all Collection framework implemented classes, such as List, Queue, Deque, and all implemented classes of the Map interface.
  4. Method names: Enumeration has longer method names (e.g., hasMoreElements() and nextElement()), while Iterator has shorter and more concise names (e.g., hasNext(), next(), and remove()).

According to Java API documentation, Iterator is preferred over Enumeration due to its additional functionality, including the remove operation and shorter method names.

Comparative Table: Enumeration vs Iterator

Here is a table comparing the differences between Enumeration and Iterator in Java:

Property Enumeration Iterator
Purpose Used in the collection framework to retrieve elements one by one. A universal cursor that can be applied to any collection object, providing both read and remove operations.
Applicability Applicable only to legacy classes like Vector, HashTable, Stack, etc.. Applicable to any collection interface, List, Queue, Deque, and Map interface.
Direction Single direction iteration. Single direction iteration, but can also perform remove operations.
Methods Contains two methods: hasMoreElements() and nextElement(). Contains three methods: hasNext(), next(), and remove().
Modifications Acts as a read-only interface, no modifications can be made to the collection while traversing. Modifications can be made, such as using the remove() method to remove an element from the collection during traversal.

In summary, Enumeration is a legacy interface used for read-only access to elements in certain collection classes, while Iterator is a more versatile and universal cursor that allows for both read and remove operations in various collection interfaces.