Course contentsShow
← Java
Lesson 1034 of 2,87024. List ImplementationsFree lesson

Enumeration: Vector's Legacy Iterator

Use the Enumeration interface with elements() method, an older alternative to Iterator.

Enumeration: Vector's Legacy Iterator

What you'll learn: How to use the older Enumeration interface to iterate through a Vector, and why it exists alongside the modern Iterator.


The Legacy Approach to Iteration

Before the Collections Framework standardized on the Iterator interface, Vector came with its own iteration mechanism: the Enumeration interface. When you call elements() on a Vector, you get an Enumeration object that lets you step through each element one by one.

Think of Enumeration as an older-style ticket dispenser at a deli counter—it hands out elements in order, but with a slightly different interface than the modern system.

How Enumeration Works

Enumeration has just two methods:

  • hasMoreElements() — checks if there are more elements to retrieve (like Iterator.hasNext())
  • nextElement() — returns the next element (like Iterator.next())

Notice what's missing: there's no remove() method. Enumeration is read-only.

Basic Usage Pattern

Vector<String> vector = new Vector<>();
vector.add("First");
vector.add("Second");
vector.add("Third");

Enumeration<String> enumeration = vector.elements();

while (enumeration.hasMoreElements()) {
    String element = enumeration.nextElement();
    System.out.println(element);
}

Why It Still Exists

Vector keeps elements() and Enumeration for backward compatibility. Older Java code written in the 1990s relies on this interface. Modern code should prefer Iterator (via vector.iterator()) or the enhanced for-loop, which are more flexible and consistent with the rest of the Collections Framework.

Key Takeaway: Enumeration is Vector's original, read-only iterator obtained via elements(), offering hasMoreElements() and nextElement() methods—it's kept for legacy compatibility but modern code should use Iterator instead.