How to get the last value of an ArrayList
To get the last value of an ArrayList in Java, you can use the size()
method to get the size of the list and then access the value at the index size() - 1
.
Here's an example:
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
int lastValue = list.get(list.size() - 1); // lastValue will be 3
Keep in mind that this will throw an IndexOutOfBoundsException
if the list is empty, so you should make sure to check whether the list is empty before attempting to access the last value.
You can also use the get(int index)
method with a negative index to get the value at the end of the list. For example, you can use list.get(-1)
to get the last value of the list. However, this syntax is less common and may not be as immediately understandable to other programmers reading your code.
Alternatively, you can use the List.subList()
method to get a view of the list as a sublist that ends at the last element of the original list, and then use the get(int index)
method on the sublist to get the last element. This is a bit more verbose but may be more efficient if you only need to access the last element once and don't need to modify the list. Here's an example:
int lastValue = list.subList(list.size() - 1, list.size()).get(0);
This will get a view of the list as a sublist that contains only the last element, and then gets the first (and only) element of the sublist.