The elementAt
method of the Vector
class is used to get the element at a specific index of the vector object.
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.
public E elementAt(int index)
The index
is the index of a vector from which the element is to be fetched. The index should be positive and less than the size of the vector
object. Otherwise, ArrayIndexOutOfBoundsException
will be thrown.
This means:
index >= 0 && index < size()
This method returns the element present at the passed index.
Please click the “Run” button below to see how the
elementAt
method works.
import java.util.Vector;class RemoveAll {public static void main( String args[] ) {// Creating VectorVector<Integer> vector = new Vector<>();// add elememtsvector.add(1);vector.add(2);vector.add(3);System.out.println("The Vector is: " + vector);// Print first elementSystem.out.println("Element at index 0 : " + vector.elementAt(0));System.out.println("Element at index 1 : " + vector.elementAt(1));System.out.println("Element at index 2 : " + vector.elementAt(2));}}
In the code above,
Line 5: We created a vector object.
Lines 8 - 10: We added three elements (1,2,3
) to the above created vector object.
Lines 15 - 17: We used the elementAt
method of the vector
object to get the element present at index 0, 1, and 2.