Table of Contents
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.
JAVAArrayList<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.
JAVAint 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:
JAVAint size = list.size();
Then we can calculate the last index, by subtracting one:
JAVAint lastIndex = size - 1;
Finally, we can get the last element by using the get()
method on the list:
JAVAint lastElement = list.get(lastIndex);
Finally, we can put this together in a single line:
JAVAint lastElement = list.get(list.size() - 1);
Here's the entire example:
JAVAimport 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);
}
}
BASH5
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!
- How to Install Node on Windows, macOS and Linux
- Create an RSS Reader in Node
- Git Tutorial: Learn how to use Version Control
- How to Set Up Cron Jobs in Linux
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Getting Started with Vuex: Managing State in Vue
- Setting Up a Local Web Server using Node.js