Traverse a collection of objects using the Enumeration Interface in Java

Java 8Object Oriented ProgrammingProgramming

All the elements in a collection of objects can be traversed using the Enumeration interface. The method hasMoreElements( ) returns true if there are more elements to be enumerated and false if there are no more elements to be enumerated. The method nextElement( ) returns the next object in the enumeration.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.util.Enumeration;
import java.util.Vector;
public class Demo {
   public static void main(String args[]) throws Exception {
      Vector vec = new Vector();
      vec.add("John");
      vec.add("Gary");
      vec.add("Susan");
      vec.add("Mike");
      vec.add("Angela");
      Enumeration enumeration = vec.elements();
      System.out.println("The vector elements are:");
      while (enumeration.hasMoreElements()) {
         Object obj = enumeration.nextElement();
         System.out.println(obj);
      }
   }
}

Output

The vector elements are:
John
Gary
Susan
Mike
Angela

Now let us understand the above program.

The Vector is created and Vector.add() is used to add the elements to the Vector. Then the vector elements are displayed using the enumeration interface. A code snippet which demonstrates this is as follows −

Vector vec = new Vector();
vec.add("John");
vec.add("Gary");
vec.add("Susan");
vec.add("Mike");
vec.add("Angela");
Enumeration enumeration = vec.elements();
System.out.println("The vector elements are:");
while (enumeration.hasMoreElements()) {
   Object obj = enumeration.nextElement();
   System.out.println(obj);
}
raja
Updated on 30-Jul-2019 22:30:24

Advertisements