In Java 21 and later, getFirst() returns the first element of an ArrayList, the one at index 0, without removing it.
It reads the same element as get(0), but it fails differently on an empty list: getFirst() throws NoSuchElementException, while get(0) throws IndexOutOfBoundsException. The name matches getFirst() 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.
getFirst() 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(0) after checking !list.isEmpty().
Syntax
Call getFirst with no arguments (Java 21+).
Java
// Java 21+
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
String first = list.getFirst(); // "a", list unchanged
String same = list.get(0); // "a" on every Java version
Call
What it does
list.getFirst()
Java 21+: the element at index 0; throws if empty.
list.get(0)
Same element on all versions.
list.isEmpty() ? null : list.get(0)
A safe read that gives null for an empty list.
list.removeFirst()
Java 21+: reads and removes the first element.
getFirst() is a constant-time read and never changes the list.
Library declarations
Java
// java.util.ArrayList<E> (since Java 21)
public E getFirst()
// Declared in SequencedCollection<E> and List<E> (Java 21)
Parameters
Parameter
Description
None
getFirst() takes no parameters.
Return Value
Return Value
Description
E
The first element. Can be null if a null is stored at index 0.
Lap times. Four Integer values start in no particular order.
Natural order.sort(null) arranges the numbers from smallest to largest.
Smallest first. After sorting, getFirst() returns the minimum, 17 seconds.
Largest last.getLast() reads the maximum, 58, from the other end of the sorted list.
Frequently Asked Questions
Java 21. It comes from the SequencedCollection interface, which List extends since that release.
It returns the same element. The difference is the exception on an empty list: NoSuchElementException for getFirst(), IndexOutOfBoundsException for get(0).
NoSuchElementException. Check isEmpty() before calling it if the list may be empty.
No. It only reads it. removeFirst() reads and removes.
Use list.get(0) after checking that the list is not empty.