Enumerate through the Vector elements in Java

Java 8Object Oriented ProgrammingProgramming

The Vector elements 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[]) {
      Vector vec = new Vector();
      vec.add(7);
      vec.add(3);
      vec.add(5);
      vec.add(9);
      vec.add(2);
      vec.add(8);
      System.out.println("The Vector elements are: ");
      Enumeration e = vec.elements();
      while (e.hasMoreElements()) {
         System.out.println(e.nextElement());
      }
   }
}

The output of the above program is as follows −

The Vector elements are:
7
3
5
9
2
8

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(7);
vec.add(3);
vec.add(5);
vec.add(9);
vec.add(2);
vec.add(8);
System.out.println("The Vector elements are: ");
Enumeration e = vec.elements();
while (e.hasMoreElements()) {
   System.out.println(e.nextElement());
}
raja
Published on 07-Feb-2019 11:54:41
Advertisements