What is the vector.firstElement method in Java?
Vector is a growable array of objects. Elements are mapped to an index. The firstElement method of the Vector class returns the first element present in the Vector object.
Syntax
public E firstElement();
This method returns the first element of the Vector object. If the Vector object is empty, then NoSuchElementException is thrown.
Example
Let’s look at an example.
import java.util.Vector;class VectorFirstElementExample {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("The first element of the Vector is : " + vector.firstElement());}}
In the code above, we created a Vector object and added three elements (1, 2, 3) using the add method. Then we called the firstElement method on the vector object in line 15, which returned the first element of the vector, 1.