Java Enumeration Interface
# Java Enumeration Interface
[Java Data Structures](#)
* * *
The Enumeration interface defines methods through which you can traverse the elements in a collection.
In Java, the Enumeration interface is located in the `java.util` package. It is a traditional, older interface that provides two main methods: `hasMoreElements()` and `nextElement()`.
This traditional interface has been superseded by the Iterator. Although Enumeration has not been deprecated, it is rarely used in modern code. Nevertheless, it is still used in methods defined by legacy classes such as `Vector` and `Properties`. Additionally, it is used in some API classes and is still widely used in applications. The following table summarizes some methods declared by Enumeration:
| **No.** | **Method Description** |
| --- | --- |
| 1 | **boolean hasMoreElements( )** Used to check if 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
```java
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationExample {
public static void main(String[] args){
// Create a Vector collection
Vector vector = new Vector();
vector.add("Apple");
vector.add("Banana");
vector.add("Orange");
// Get the Enumeration object
Enumeration enumeration = vector.elements();
// Traverse collection elements using Enumeration
while(enumeration.hasMoreElements()){
String element = enumeration.nextElement();
System.out.println(element);
}
}
}
In the code above, we first create a `Vector` collection and use the `elements()` method to obtain an `Enumeration` object. Then, we use the `hasMoreElements()` and `nextElement()` methods to traverse the elements in the collection.
## Example 2
```java
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());
}
}
}
The compiled and running result of the above example is as follows:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
* * Java Data Structures](#)
YouTip