Java Vector elementAt() Method
Last Updated :
14 Jan, 2025
Improve
In Java, the elementAt() method is used to fetch or retrieve an element at a specific index from a Vector. It allows to access elements in the vector by providing the index, which is zero-based.
Example 1: Here, we use the elementAt() method to retrieve an element at a specified index with an Integer type.
// Java program to Demonstrate the
// use of elementAt() with Integer type
import java.util.Vector;
public class Geeks {
public static void main(String args[])
{
// Creating an empty Vector
Vector<Integer> v = new Vector<>();
// Use add() method to
// add elements in the Vector
v.add(10);
v.add(20);
v.add(30);
v.add(40);
v.add(50);
System.out.println(" " + v);
// Fetching the specific element from the Vector
System.out.println(" The element is: "
+ v.elementAt(3));
}
}
Output
[10, 20, 30, 40, 50] The element is: 40
Syntax of Vector element() Method
public E elementAt(int index)
- Parameter: index: It specifies the position of the element we want to retrieve.
- Return Type: It returns the element present at the position specified.
Example 2: Here, we use the elementAt() method to retrieve an element at a specified index with String type.
// Java program to Demonstrate the use of elementAt() with String type
import java.util.Vector;
public class Geeks {
public static void main(String args[])
{
// Creating an empty Vector
Vector<String> v = new Vector<>();
// Use add() method to
// add elements in the Vector
v.add("Geeks");
v.add("for");
v.add("Geeks");
System.out.println(" " + v);
// Fetching the specific element from the Vector
System.out.println(" The element is: "
+ v.elementAt(1));
}
}
Output
[Geeks, for, Geeks] The element is: for