Java Enumeration Interface: Legacy Collection Iteration Explained

Explore the Java Enumeration interface, used for enumerating elements in legacy collections like Vector and Properties. Although considered outdated and replaced by the Iterator interface, Enumeration remains relevant in many legacy applications. Learn about the methods defined by the Enumeration interface for object collection iteration.



Java - Enumeration Interface

The Enumeration interface defines methods for enumerating (obtaining one element at a time) the elements of a collection of objects. Although this interface is considered obsolete for new code and has been superseded by Iterator, it is still widely used in legacy classes such as Vector and Properties and remains in use across various applications.

Enumeration Interface Methods

The Enumeration interface declares the following methods:

Sr.No. Method & Description
1 boolean hasMoreElements()
Returns true if there are more elements to extract; otherwise, returns false when all elements have been enumerated.
2 Object nextElement()
Returns the next object in the enumeration as a generic Object reference.

Example 1: Enumeration for Vector

The following example demonstrates the usage of Enumeration with a Vector.

Enumeration for Vector

import java.util.Vector;
import java.util.Enumeration;

public class EnumerationTester {

public static void main(String args[]) {
    Enumeration days;
    Vector dayNames = new Vector<>();
    
    dayNames.add("Sunday");
    dayNames.add("Monday");
    dayNames.add("Tuesday");
    dayNames.add("Wednesday");
    dayNames.add("Thursday");
    dayNames.add("Friday");
    dayNames.add("Saturday");
    days = dayNames.elements();
    
    while (days.hasMoreElements()) {
        System.out.println(days.nextElement()); 
    }
}
}
Output

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Example 2: Enumeration for Properties

The following example demonstrates the usage of Enumeration with Properties to print property values.

Enumeration for Properties

import java.util.Properties;
import java.util.Enumeration;

public class EnumerationTester {

public static void main(String args[]) {
    Enumeration days;
    Properties dayNames = new Properties();
    
    dayNames.put(1, "Sunday");
    dayNames.put(2,"Monday");
    dayNames.put(3,"Tuesday");
    dayNames.put(4,"Wednesday");
    dayNames.put(5,"Thursday");
    dayNames.put(6,"Friday");
    dayNames.put(7,"Saturday");
    days = dayNames.elements();
    
    while (days.hasMoreElements()) {
        System.out.println(days.nextElement()); 
    }
}
}






Output

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Conclusion

While the Enumeration interface has been largely replaced by the more versatile Iterator, it remains useful in certain legacy classes and applications. It provides a simple way to traverse elements in collections like Vector and Properties while maintaining compatibility with older codebases.