Home » Core Java » util » Vector » Vector Enumeration example

About Ilias Tsagklis

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

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.

(No Ratings Yet)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar
  Subscribe  
Notify of