How to get the Last Element of an ArrayList in Java

Updated onbyAlan Morel
How to get the Last Element of an ArrayList in Java

Java has a robust library of pre-written data structures. One of more popular ones is an ArrayList.

An ArrayList is a list that grows and shrinks dynamically, and in many cases, you'll want to be able to get the last element in the list.

In this post, we'll learn exactly how to do this.

Getting the Last Element in an ArrayList

To start, let's initialize an ArrayList. There are many ways to do this, but in this example, we're going to use the asList() method on the Arrays class.

This method takes in a list as parameters, and returns an ArrayList with the same elements.

JAVA
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));

ArrayLists come with a method called get() which takes in a position as a parameter that represents the index of the element you want returned.

For example, since arrays are zero-indexed, the first element in the list is at index 0.

JAVA
int firstElement = list.get(0);

However, in this post, we want to get the last element. We can do this by subtracting 1 from the size of the list, since that should return us the last element.

This is how to get the size of the list:

JAVA
int size = list.size();

Then we can calculate the last index, by subtracting one:

JAVA
int lastIndex = size - 1;

Finally, we can get the last element by using the get() method on the list:

JAVA
int lastElement = list.get(lastIndex);

Finally, we can put this together in a single line:

JAVA
int lastElement = list.get(list.size() - 1);

Here's the entire example:

JAVA
import java.util.Arrays; import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5)); int lastElement = list.get(list.size() - 1); System.out.println(lastElement); } }
BASH
5

Conclusion

In this post, we saw how to get the last element in an ArrayList. The process is simple, just use the get() method on the list and pass it the length of the entire list, minus one.

Hopefully, you've found this useful to you. Happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.