Java Program to demonstrate the use of Enumeration.
Objective
Write a Java program to demonstrate the legacy Enumeration interface with a Vector.
Algorithm / Approach
- Create a
Vectorand add the days of the week to it. - Extract an
Enumerationobject usingdays.elements(). - Use a
whileloop with the conditiond.hasMoreElements(). - Retrieve the data using
d.nextElement().
Test.java
import java.util.*;
class Test{
public static void main(String[] a)
{
Enumeration d;
Vector days = new Vector();
days.add("Sunday");
days.add("Monday");
days.add("Tuesday");
days.add("Wednesday");
days.add("Thursday");
days.add("Friday");
days.add("Saturday");
d = days.elements();
while (d.hasMoreElements()) {
System.out.println(d.nextElement());
}
}
}
Expected Output
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
Explanation of the Program
Enumerationis a legacy interface from Java 1.0. It was the original way to iterate over collections before the Java Collections Framework (and theIteratorinterface) was introduced in Java 1.2.Vectoris also a legacy class (a synchronized, thread-safe version of ArrayList).- While you will rarely write new code using these classes today, you will frequently encounter them when maintaining older legacy Java enterprise applications.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)