DEV Community

Sudhakar V
Sudhakar V

Posted on

Enumeration in Java

In Java, Enumeration is a legacy interface used to traverse (iterate) through legacy collection classes like Vector, Hashtable, Stack, and Properties. It was introduced in JDK 1.0, before the modern Iterator interface was added in JDK 1.2.


๐Ÿ”น Declaration of Enumeration Interface

public interface Enumeration<E> {
    boolean hasMoreElements();  // Checks if more elements exist
    E nextElement();            // Returns the next element
}
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Common Use Cases

Enumeration is typically used with legacy collections such as:

  • Vector
  • Stack
  • Hashtable
  • Properties

๐Ÿ”น Example: Enumeration with Vector

import java.util.*;

public class EnumerationExample {
    public static void main(String[] args) {
        Vector<String> vector = new Vector<>();
        vector.add("Apple");
        vector.add("Banana");
        vector.add("Cherry");

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

        while (enumeration.hasMoreElements()) {
            System.out.println(enumeration.nextElement());
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

โœ… Output:

Apple
Banana
Cherry
Enter fullscreen mode Exit fullscreen mode

๐Ÿ”น Limitations of Enumeration

Limitation Description
Read-only Cannot add or remove elements
Forward-only traversal No support for backward movement
Legacy interface Use Iterator/ListIterator for modern collections
No fail-fast behavior Doesn't throw exceptions on concurrent modification

๐Ÿ”น Enumeration vs Iterator

Feature Enumeration Iterator
Introduced in JDK 1.0 JDK 1.2
Applicable to Legacy classes only All Collection types
Remove support โŒ Not supported โœ… Supported
Direction Forward only Forward only (Iterator), both with ListIterator
Safety Not fail-fast Fail-fast

๐Ÿ”น Where Is Enumeration Still Used?

Even though it's outdated, you may still encounter it:

  • In legacy codebases.
  • With certain classes like Properties, ResourceBundle, or ClassLoader.
  • When using APIs that return Enumeration (e.g., ClassLoader.getResources()).

๐Ÿ”น Modern Alternative: Iterator

If you're using modern List, Set, or Map, prefer:

Iterator<String> it = list.iterator();
while (it.hasNext()) {
    System.out.println(it.next());
}
Enter fullscreen mode Exit fullscreen mode

โœ… Summary

  • Enumeration is simple but limited.
  • Best used with legacy collections.
  • For modern code, use Iterator or ListIterator.

Would you like an example using Enumeration with a Hashtable or Properties file?

Top comments (0)