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 = newArrayList<>(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
intfirstElement= 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
intsize= list.size();
Then we can calculate the last index, by subtracting one:
JAVA
intlastIndex= size - 1;
Finally, we can get the last element by using the get() method on the list:
JAVA
intlastElement= list.get(lastIndex);
Finally, we can put this together in a single line:
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!