Java Enumeration Interface

Java 数据结构Java Data Structures


The Enumeration interface defines some methods through which elements in a collection can be traversed.

In Java, the Enumeration interface is located in the java.util package. It is a traditional, old interface that provides two main methods: hasMoreElements() and nextElement().

This traditional interface has been replaced by iterators. Although Enumeration has not been abandoned, it is rarely used in modern code. Nevertheless, it is still used in methods defined by traditional classes such as Vector and Properties. In addition, it is also used in some API classes and is widely used in applications. The following table summarizes some of the methods declared by Enumeration:

No. Method Description
1 boolean hasMoreElements( )
Used to check whether there are more elements in the enumeration. Returns true if the enumeration contains more elements, otherwise returns false.
2 Object nextElement( )
Used to get the next element in the enumeration. Returns the next element in the enumeration.

Example

The following example demonstrates the use of Enumeration:

Example

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

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

        // Get an Enumeration object
        Enumeration<String> enumeration = vector.elements();

        // Use Enumeration to traverse collection elements
        while (enumeration.hasMoreElements()) {
            String element = enumeration.nextElement();
            System.out.println(element);
        }
    }
}

In the above code, we first created a Vector collection and used the elements() method to obtain an Enumeration object. Then, we used the hasMoreElements() and nextElement() methods to traverse the elements in the collection.

Example 2

import java.util.Vector; import java.util.Enumeration; public class EnumerationTester { public static void main(String args[]) { Enumeration<String> days; Vector<String> dayNames = new Vector<String>(); 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()); } } }

The compilation and running result of the above example is as follows:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

Java 数据结构Java Data Structures

Other Extensions