The
Vector
class is a growable array of objects. The elements ofVector
can be accessed using an integer index and the size of aVector
can be increased or decreased. Read more aboutVector
here.
elements()
method in Vector
?The elements()
method can be used to get all the values of the Vector
object as an Enumeration
object.
public Enumeration<V> elements()
This method doesn’t take any arguments.
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
.
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() + ",");}}}
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.