In the process of enumeration, the elements of a collection are retrieved one by one.
The enumeration interface defines the methods we can use to enumerate the elements in a
Enumeration is regarded as outdated in new code. Various historical class methods, such as Vector, and several
The
elements()
method of theVector
class returns an enumeration of the vector elements.
Important points about the interface:
The enumeration interface retrieves elements in a forwarding direction.
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 |
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());}}}