How to get the first element of an ArrayList in Java
In this tutorial, we are going to learn about how to get the first element of an ArrayList in Java.
Consider, we have a following ArrayList:
List<Integer> list = Arrays.asList(10, 20, 30, 40);
To get the first element of a ArrayList, we can use the list.get()
method by passing 0
as an argument.
0 is refers to first element index.
Here is an example, that returns the first element 10
from the following ArrayList:
import java.util.Arrays;
import java.util.List;
public class Main
{
public static void main(String[] args) {
List<Integer> list = Arrays.asList(10, 20, 30, 40);
System.out.println(list.get(0));
}
}
Output:
10