What is the Vector.elements method in Java?

The Vector class is a growable array of objects. The elements of Vector can be accessed using an integer index and the size of a Vector can be increased or decreased. Read more about Vector here.

What is the elements() method in Vector?

The elements() method can be used to get all the values of the Vector object as an Enumeration object.

Syntax

public Enumeration<V> elements()

Parameters

This method doesn’t take any arguments.

Return value

The elements() method will return an Enumeration for the values of the Vector. In the returned Enumeration, the items are generated based on the index. For example, the first item generated will be the element at index 0.

Code

The example below shows how to use the elements() method.

import java.util.Vector;
import java.util.Enumeration;
class ElementsExample {
public static void main( String args[] ) {
Vector<Integer> vector = new Vector<>();
vector.add(1);
vector.add(2);
vector.add(3);
System.out.println("The Vector is :" + vector);
Enumeration<Integer> elements = vector.elements();
System.out.print("The values are : ");
while(elements.hasMoreElements()) {
System.out.print(elements.nextElement() + ",");
}
}
}

Explanation

In the code above:

  • In lines 1 and 2, we import the Vector and Enumeration classes.

  • In line 6, we create a new object for the Vector class with the name vector.

  • In lines 7 to 9, we use the add method to add three elements 1,2,3 into the vector object.

  • In line 12, we get the values present in the vector using the elements() method and store them in the elements variable. Then, we print the elements object by using the while loop, hasMoreElements, and nextElement methods.

Free Resources