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)