In Java, peekFirst() returns the head (first element) of an ArrayDeque without removing it. If the deque is empty, it returns null.
It is the "special value" version of getFirst(), and peek() does exactly the same. Its mirror at the tail is peekLast().
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.
Syntax
Call peekFirst with no arguments.
Java
Deque<String> deque = new ArrayDeque<>();
String head = deque.peekFirst(); // null (empty)
deque.add("x");
head = deque.peekFirst(); // "x"
Call
What it does
deque.peekFirst()
Returns the head, or null.
deque.getFirst()
Returns the head; throws if empty.
deque.peek()
Same as peekFirst().
deque.pollFirst()
Returns the head and removes it.
Because an ArrayDeque cannot hold null, a null from peekFirst() is a reliable "empty" signal.
Library declarations
Java
// java.util.ArrayDeque<E>
public E peekFirst()
// Declared in Deque<E>
Parameters
Parameter
Description
None
peekFirst() takes no parameters.
Return Value
Return Value
Description
E
The head of the deque, left in place.
null
If the deque is empty.
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 peekFirst().