To access an element in a list at a specific index in Java, you can use the get()
method of the List interface.
In this example,
java.util.List
and java.util.ArrayList
.numbers
using ArrayList
and add integer elements to it.get()
method with index 2 as the argument: numbers.get(2)
.System.out.println()
.import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
int elementAtIndex2 = numbers.get(2);
System.out.println("Element at index 2 is: " + elementAtIndex2);
}
}
Element at index 2 is: 30
In this tutorial, we learned How to get Element in a List at a Specific Index in Java language with well detailed examples.