Vector

Vector Enumeration example

This is an example of how to obtain a Vector Enumeration in Java.
Obtaining a Vector Enumeration implies that you should:

  • Create a new Vector.
  • Populate the vector with elements, with add(E e) API method of Vector.
  • Invoke elements() API method of Vector to get an Enumeration of the Vector’s elements.
  • Enumerate through the elements of an Enumeration, with hasMoreElements(), nextElement() methods of Enumeration.

Let’s take a look at the code snippet that follows:

package com.javacodegeeks.snippets.core;
 
import java.util.Vector;
import java.util.Enumeration;
 
public class VectorEnumeration {
 
  public static void main(String[] args) {

    // Create a Vector and populate it with elements
    Vector vector = new Vector();
    vector.add("element_1");
    vector.add("element_3");
    vector.add("element_5");
    vector.add("element_2");
    vector.add("element_4");
 
    // elements() method returns an Enumeration of Vector's elements 
    Enumeration vectorElementsEnum = vector.elements();
 
    /*

To enumerate through the elements of an Enumeration we can use the 

boolean hasMoreElements() and Object nextElement() methods. The 

first one returns true if there are more elements to enumerate through 

otherwise it returns false. The second returns the next element in enumeration.
    */
 
    System.out.println("Vector elements : ");
 
    while(vectorElementsEnum.hasMoreElements())

System.out.println(vectorElementsEnum.nextElement());
  }
}

Output:

Vector elements : 
element_1
element_3
element_5
element_2
element_4

 
This was an example of how to obtain a Vector Enumeration in Java.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button