What is the Vector.elements method in Java?
The
Vectorclass is a growable array of objects. The elements ofVectorcan be accessed using an integer index and the size of aVectorcan be increased or decreased. Read more aboutVectorhere.
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
VectorandEnumerationclasses. -
In line 6, we create a new object for the
Vectorclass with the namevector. -
In lines 7 to 9, we use the
addmethod to add three elements1,2,3into thevectorobject. -
In line 12, we get the values present in the
vectorusing theelements()method and store them in theelementsvariable. Then, we print theelementsobject by using thewhileloop, hasMoreElements, and nextElement methods.