by Sai gowtham

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, we can use the list.get(list.size()-1) method in Java.

The size() method returns the total number of elements in the ArrayList, so list.size()-1 returns the last element index.

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

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
130,921 students enrolled
48.5 hours of video content
View Course