How to get the last element of an ArrayList in Java
In this tutorial, we are going to learn about how to get the last element of an ArrayList in Java.
Consider, we have a following ArrayList:
List<Integer> list = Arrays.asList(10, 20, 30, 40);
To get the last element of a ArrayList in Java, we can use the list.get()
method by passing its index list.size()-1
.
Here is an example, that returns the last element 40
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(list.size()-1));
}
}
Output:
40