Trusted answers to developer questions

What is enumeration interface in Java?

Get Started With Data Science

Learn the fundamentals of Data Science with this free course. Future-proof your career by adding Data Science skills to your toolkit — or prepare to land a job in AI, Machine Learning, or Data Analysis.

What is enumeration?

In the process of enumeration, the elements of a collection are retrieved one by one.

What is the enumeration interface?

The enumeration interface defines the methods we can use to enumerate the elements in a collectionobjects that group multiple elements into a single unit..

Enumeration is regarded as outdated in new code. Various historical class methods, such as Vector, and several APIApplication Programming Interface. classes and application code, use the enumeration interface.

The elements() method of the Vector class returns an enumeration of the vector elements.

Important points about the interface:

  1. The enumeration interface retrieves elements in a forwarding direction.

  2. The interface doesn’t support modification of the collection during the retrieval.

The interface exposes three methods as seen below.

Method name Purpose
hasMoreElements() Tests if the enumeration contains more elements
nextElement() Returns the next element of the enumeration
asIterator() Returns an iterator for the remaining elements of the enumeration

Code

The code implementation below shows how to use enumeration in Java.

import java.util.Enumeration;
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> stringVector = new Vector<>();
stringVector.add("one");
stringVector.add("two");
stringVector.add("three");
Enumeration<String> stringEnumeration = stringVector.elements();
while(stringEnumeration.hasMoreElements()){
System.out.println(stringEnumeration.nextElement());
}
}
}

RELATED TAGS

java
enumeration
interface
Did you find this helpful?