In Java, poll() removes the head of an ArrayDeque and returns it. If the deque is empty, it returns null instead of throwing an exception.
It comes from the Queue interface and does the same thing as pollFirst(). Together with offer() and peek() it forms the usual first-in, first-out queue.
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 poll with no arguments and check the result for null.
Java
Queue<String> queue = new ArrayDeque<>(Arrays.asList("a", "b"));
String head = queue.poll(); // "a"
String next = queue.poll(); // "b"
String none = queue.poll(); // null (queue is empty)
Call
What it does
queue.poll()
Removes and returns the head, or null if empty.
queue.remove()
Same, but throws NoSuchElementException if empty.
deque.pollFirst()
The Deque name for the same operation.
queue.peek()
Returns the head without removing it.
poll() always works at the head, no matter how the elements got there. If they were added with push, the head is the most recently pushed element.
Library declarations
Java
// java.util.ArrayDeque<E>
public E poll()
// Declared in Queue<E> and Deque<E>
Parameters
Parameter
Description
None
poll() 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 poll().