In Java, getFirst() returns the head (first element) of an ArrayDeque without removing it. If the deque is empty, it throws NoSuchElementException.
It is the throwing version of peekFirst(), and element() does exactly the same. For a stack built with push, getFirst() reads the top.
An instance method of java.util.ArrayDeque (Java 1.6+): a resizable-array deque with no capacity limit, no null elements, and no thread safety. Since Java 21, getFirst is also declared by the SequencedCollection interface, which Deque extends.
Syntax
Call getFirst with no arguments.
Java
Deque<String> deque = new ArrayDeque<>(Arrays.asList("north", "east"));
String first = deque.getFirst(); // "north", deque unchanged
Call
What it does
deque.getFirst()
Returns the head; throws if empty.
deque.peekFirst()
Returns the head, or null if empty.
deque.element()
Same as getFirst().
deque.removeFirst()
Returns the head and removes it.
getFirst() is a constant-time read. It never changes the deque, so you can call it as often as you like.
Library declarations
Java
// java.util.ArrayDeque<E>
public E getFirst()
// Declared in Deque<E> (and SequencedCollection<E> since Java 21)
Parameters
Parameter
Description
None
getFirst() takes no parameters.
Return Value
Return Value
Description
E
The head of the deque. Never null.
Throw or Return a Special Value?
Each end has a method that throws when it cannot work (such as on an empty deque) and one that returnsnull or false instead. The highlighted cell matches getFirst().