The Enumeration interface in Java is one of the legacy interfaces used to iterate over elements of collections such as Stack, Vector and HashTable. It was introduced in JDK 1.0 and is part of the java.util package
It is a legacy cursor used before Iterator and ListIterator.
It supports only forward direction traversal (one-way).
Enumeration is not fail-fast, so it does not throw ConcurrentModificationException even if the collection is modified during iteration.
Mostly used with Vector, Stack, and Hashtable classes.
Declaration
public interface Enumeration<E>
Where E is the type of elements stored in a collection.
Creating Enumeration Object
Creating an Enumeration Object with the Vector class
Vector v = new Vector(); Enumeration e = v.elements();
Output
Elements of Vector:
Apple
Banana
Cherry
Explanation
The elements() method of the Vector class returns an Enumeration of the vector’s elements.
The hasMoreElements() method checks if more elements exist in the collection.
The nextElement() method retrieves the next element and advances the cursor.
The iteration continues until all elements are processed.
Methods of Enumeration Interface
asIterator(): This method returns an Iterator which traverses all the remaining elements covered by this enumeration.
hasMoreElements(): It returns a boolean indicating whether more elements remain; returns false when all elements are traversed.
nextElement(): It returns the next element in the enumeration sequence
Example: Using Enumeration with Hashtable
Output
Hashtable Keys:
3 -> C++
2 -> Python
1 -> Java
Working of Enumeration
Let’s understand the working process of the Enumeration cursor step-by-step. Suppose we have a Vector of three elements — Apple, Banana, and Cherry
Step 1: Before Iteration
The cursor lies before the first element.
hasMoreElements() -> returns true (next element exists).
Calling nextElement() returns "Apple" and moves the cursor forward.