In Java, offerFirst(e) inserts an element at the head (front) of an ArrayDeque and returns true. It puts the element in the same place as addFirst(e) and push(e).
It belongs to the "special value" family of Deque methods. On a deque with a size limit it would return false when full. An ArrayDeque is never full, so it always returns true.
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 offerFirst with the element that should become the new head.
Java
Deque<String> deque = new ArrayDeque<>();
deque.offer("b");
boolean ok = deque.offerFirst("a"); // true, deque = [a, b]
Call
What it does
deque.offerFirst(e)
Inserts e at the head and returns true.
deque.addFirst(e)
Same position, returns nothing.
deque.push(e)
Same position, stack-style name, returns nothing.
deque.offerFirst(null)
Throws NullPointerException.
Choosing between offerFirst and addFirst on an ArrayDeque is mostly a matter of style. Code written against the Deque interface often prefers offerFirst so it also behaves well with capacity-limited deques.
Library declarations
Java
// java.util.ArrayDeque<E>
public boolean offerFirst(E e)
// Declared in Deque<E>
Parameters
Parameter
Description
e
Required. The element to insert at the head. Must not be null.
Return Value
Return Value
Description
boolean
Always true for an ArrayDeque.
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 offerFirst().