Java Enumeration Interface
The Enumeration interface defines some 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, old interface that provides two main methods: hasMoreElements() and nextElement().
This traditional interface has been replaced by iterators. Although Enumeration has not been deprecated, it is rarely used in modern code. Nevertheless, it is still used in methods defined by traditional classes such as Vector and Properties, and it is also used in some API classes and widely in applications. The following table summarizes some 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 the Enumeration object
Enumeration
<
String
enumeration
=
vector.
elements
(
)
;
// Traverse the collection elements using Enumeration
while
(
enumeration.
hasMoreElements
(
)
)
{
String
element
=
enumeration.
nextElement
(
)
;
System
.
out
.
println
(
element
)
;
}
}
}
In the code above, 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 execution results of the above example are as follows:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Java Data Structures