In Java, offerFirst(e) inserts the element at the front of the LinkedList and returns true. It belongs to the Deque interface, which describes a "double-ended queue".
The Deque contract lets a bounded deque answer false when it is full. A LinkedList has no size limit, so it always answers true, and the call acts just like addFirst(e).
An instance method of java.util.LinkedList (since Java 1.6): call it on a LinkedList object. Add import java.util.LinkedList; at the top of your file. It is declared by Deque, and LinkedList implements it. Call it on a LinkedList (or Deque) variable: a plain List variable cannot see it.
Syntax
Pass the element for the front position.
Java
LinkedList<String> list = new LinkedList<>();
boolean a = list.offerFirst("B"); // true, [B]
boolean b = list.offerFirst("A"); // true, [A, B]
Call
What it does
list.offerFirst(e)
Inserts e at the head and returns true.
list.addFirst(e)
Same effect, with no return value.
list.push(e)
Same effect, under the stack name.
list.offerLast(e)
Inserts at the tail instead.
The result is always true for a LinkedList. Use it when your code is written against the Deque interface and must also work with bounded deques.
Library declarations
Java
// java.util.LinkedList
public boolean offerFirst(E e)
Parameters
Parameter
Description
e (E)
The element to insert at the front. It may be null.
Letters a to d. The loop walks through four characters and gives each one to both lists.
Reverse order in both. Every new letter goes to the front, so the lists read d, c, b, a.
Identical results. The two lists contain exactly the same sequence.
That is why equals is true. The only difference between the methods is that offerFirst also returns true.
Frequently Asked Questions
It inserts the element at the front (head) of the list and returns true.
The effect on a LinkedList is the same. offerFirst returns true, and addFirst returns nothing. For bounded deques, offerFirst returns false when full while addFirst throws an exception.
No. A LinkedList is never full, so the result is always true.
No. It is declared by the Deque interface, so the variable must be a Deque or a LinkedList.
A LinkedList accepts null. An ArrayDeque does not, and throws a NullPointerException.