Enumerate through the Vector elements in Java


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());
}

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jun-2020

523 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements