In Java 21 and later, getLast() returns the last element of an ArrayList, the one at index size() - 1, without removing it.
Before Java 21 you had to write list.get(list.size() - 1), which is easy to get wrong by one. getLast() reads the same element, throws NoSuchElementException on an empty list, and matches getLast() on Deque and LinkedList.
An instance method of java.util.ArrayList, added in Java 21. It was added to List through the new SequencedCollection interface, and ArrayList overrides it.
Java 21+ only.
getLast() comes from the SequencedCollection interface added in Java 21 (JEP 431). The examples on this page need JDK 21 or newer; on Java 8, 11, or 17 the call fails to compile with "cannot find symbol". On older versions, use get(list.size() - 1) after checking !list.isEmpty().
Syntax
Call getLast with no arguments (Java 21+).
Java
// Java 21+
List<Integer> list = new ArrayList<>(Arrays.asList(10, 20, 30));
int last = list.getLast(); // 30, list unchanged
int same = list.get(list.size() - 1); // 30 on every Java version
Call
What it does
list.getLast()
Java 21+: the last element; throws if empty.
list.get(list.size() - 1)
Same element on all versions.
list.get(list.size())
Off-by-one bug: always IndexOutOfBoundsException.
list.removeLast()
Java 21+: reads and removes the last element.
getLast() is a constant-time read; it does not walk the list and does not change it.
Library declarations
Java
// java.util.ArrayList<E> (since Java 21)
public E getLast()
// Declared in SequencedCollection<E> and List<E> (Java 21)
Parameters
Parameter
Description
None
getLast() takes no parameters.
Return Value
Return Value
Description
E
The last element. Can be null if a null is stored there.