An enumeration is an object that generates elements one at a time, used for passing through a collection, usually of unknown size. The traversing of elements can only be done once per creation.
In Java, the term “Enumeration” usually refers to the legacy interface java.util.Enumeration
. This interface was part of the original Java Collections Framework and is now considered somewhat outdated, as it has been largely superseded by the more versatile Iterator interface introduced in Java 2 (JDK 1.2).
Enumeration
has two main methods:
boolean hasMoreElements()
: This method returns true if the enumeration contains more elements; otherwise, it returns false.Object nextElement()
: This method returns the next element in the enumeration.
Here is a simple example of using Enumeration
:
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationExample {public static void main(String[] args) {
// Creating a Vector
Vector<String> vector = new Vector<>();
vector.add(“Java”);
vector.add(“Python”);
vector.add(“C++”);
// Obtaining an Enumeration from the Vector
Enumeration<String> enumeration = vector.elements();
// Iterating through the elements using Enumeration
while (enumeration.hasMoreElements()) {
String element = enumeration.nextElement();
System.out.println(element);
}
}
}
It’s important to note that for modern code, using the enhanced for loop or the Iterator interface is generally preferred over Enumeration
.