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!
- Managing PHP Dependencies with Composer
- Getting Started with Express
- Getting Started with Electron
- How to deploy a .NET app using Docker
- Best Visual Studio Code Extensions for 2022
- Getting Started with Deno
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Getting Started with React