Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to demonstrate the use of Enumeration.

Java Code Example — Collection Programs

ADVERTISEMENT

Java Program to demonstrate the use of Enumeration.

Objective

Write a Java program to demonstrate the legacy Enumeration interface with a Vector.

Algorithm / Approach

  1. Create a Vector and add the days of the week to it.
  2. Extract an Enumeration object using days.elements().
  3. Use a while loop with the condition d.hasMoreElements().
  4. 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

  • Enumeration is a legacy interface from Java 1.0. It was the original way to iterate over collections before the Java Collections Framework (and the Iterator interface) was introduced in Java 1.2.
  • Vector is 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)
ADVERTISEMENT