W3docs

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.

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:


import java.util.ArrayList;

ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);

if (!list.isEmpty()) {
    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.