In Java, pollFirst() removes the head (first element) of an ArrayDeque and returns it, or returns null if the deque is empty.
It is the "special value" version of removeFirst(), and the Deque name for poll(). Its mirror at the tail is pollLast().
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 pollFirst with no arguments.
Java
Deque<Integer> deque = new ArrayDeque<>(Arrays.asList(1, 2, 3));
Integer head = deque.pollFirst(); // 1, deque = [2, 3]
Call
What it does
deque.pollFirst()
Removes and returns the head, or null.
deque.poll()
Same operation, Queue name.
deque.removeFirst()
Same, but throws when empty.
deque.pollLast()
Removes from the tail instead.
Store the result in a wrapper type such as Integer or String and test it for null before using it. This lets you write loops without a separate isEmpty() check.
Library declarations
Java
// java.util.ArrayDeque<E>
public E pollFirst()
// Declared in Deque<E>
Parameters
Parameter
Description
None
pollFirst() takes no parameters.
Return Value
Return Value
Description
E
The former head element.
null
If the deque was 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 pollFirst().