Java Enumeration Interface
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.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
The compilation and running result of the above example is as follows:
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Other Extensions
Java Data Structures