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
}
๐น Common Use Cases
Enumeration is typically used with legacy collections such as:
VectorStackHashtableProperties
๐น 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());
}
}
}
โ
Output:
Apple
Banana
Cherry
๐น 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, orClassLoader. - 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());
}
โ Summary
-
Enumerationis simple but limited. - Best used with legacy collections.
- For modern code, use
IteratororListIterator.
Would you like an example using Enumeration with a Hashtable or Properties file?
Top comments (0)