Home Java LinkedList Methods addFirst() Java LinkedList addFirst() Method Definition In Java, addFirst(e) inserts the element at the front of the LinkedList. The old first element becomes the second one, and the list grows by one.
Because the list is a chain of nodes with a link to the head, this takes the same small amount of time however long the list is. That is a big advantage over an ArrayList, which has to shift every element.
An instance method of java.util.LinkedList (since Java 1.2): 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 to place at the front.
LinkedList<String> list = new LinkedList<>();
list.add("B");
list.addFirst("A"); // [A, B]
list.addFirst("Z"); // [Z, A, B] Call What it does list.addFirst(e)Inserts e at the head. Returns nothing. list.push(e)The stack name for the same action. list.offerFirst(e)The same action, but it returns true. list.add(0, e)Also inserts at the front, through the List interface.
addFirst never fails for a size reason. A LinkedList has no capacity limit, and it accepts null.
Library declarations // java.util.LinkedList
public void addFirst(E e) Parameters Parameter Description e (E)The element to insert at the front. It may be null.
Return Value Return Value Description voidNothing is returned.
Important
The variable must be declared as LinkedList (or Deque), not as List. The List interface of Java 8 has no addFirst method, so a List<String> variable will not compile when you call it. Use add(0, e) if you only have a List.
Compare with Similar Methods Ways to put an element at the front:
Method How it differs push(e)Does exactly the same work, under the stack name. offerFirst(e)Same effect, but returns true, like other queue methods. addLast(e)Puts the element at the other end. ArrayDeque.addFirst()The same method on an array-based deque, which does not allow null.
Java Examples 1. Insert at the front 2. Recent items first 3. Null and the List type Example 1 — Put New Items at the Front of a List Add a few names with addFirst and watch the order flip.
import java.util.LinkedList;
public class LinkedListAddFirstDemo {
public static void main(String[] args) {
LinkedList<String> line = new LinkedList<>();
line.addFirst("Cara");
System.out.println("step 1: " + line);
line.addFirst("Ben");
System.out.println("step 2: " + line);
line.addFirst("Ann");
System.out.println("step 3: " + line);
System.out.println("head: " + line.getFirst());
}
} step 1: [Cara]
step 2: [Ben, Cara]
step 3: [Ann, Ben, Cara]
head: Ann How It Works An empty list. The first addFirst makes "Cara" the only element, so it is both first and last.Newest goes to the front. "Ben" is placed before "Cara", so the list reads Ben, Cara.The order reverses. After "Ann" is added, the names are in the opposite order from how they were added.getFirst confirms it. The head of the list is the element added last, "Ann".Example 2 — Keep the Latest Page at the Top of a History Model a browser history where each visited page goes to the front, and trim the list when it gets long.
import java.util.LinkedList;
public class LinkedListAddFirstHistory {
public static void main(String[] args) {
LinkedList<String> history = new LinkedList<>();
String[] visits = {"home", "docs", "blog", "pricing"};
for (String page : visits) {
history.addFirst(page);
if (history.size() > 3) {
history.removeLast();
}
System.out.println("visited " + page + " -> " + history);
}
}
} visited home -> [home]
visited docs -> [docs, home]
visited blog -> [blog, docs, home]
visited pricing -> [pricing, blog, docs] How It Works One page per loop. Each visited page is pushed to the front, so the latest page is always first.The list grows to three. After "home", "docs" and "blog" it holds three pages.A fourth page forces a trim. Adding "pricing" makes four items, so removeLast() drops the oldest page, "home".Both ends in constant time. Adding at the front and removing at the back are the two things a LinkedList does best.Example 3 — Add null at the Front and Compare with add(0, e) Show that null is accepted, and that add(0, e) gives the same list.
import java.util.LinkedList;
import java.util.List;
public class LinkedListAddFirstNull {
public static void main(String[] args) {
LinkedList<String> deque = new LinkedList<>();
deque.add("middle");
deque.addFirst(null);
System.out.println("with null: " + deque);
List<String> asList = new LinkedList<>();
asList.add("middle");
asList.add(0, "front");
System.out.println("add(0, e): " + asList);
deque.addFirst("front");
System.out.println("same shape: " + deque.equals(asList));
}
} with null: [null, middle]
add(0, e): [front, middle]
same shape: false How It Works null is a legal element. addFirst(null) puts a null at the head, and the list prints it as null.A List variable has no addFirst. For asList, which is typed as List, the way to insert at the front is add(0, "front").Another insert at the front. deque.addFirst("front") now puts "front" before the null.The lists are not equal. The first list still has a null element, so equals prints false even though both start with "front".Frequently Asked Questions How do I add an element to the beginning of a LinkedList in Java? Call list.addFirst(element). It places the element at the head, and all other elements move one position back.
Is addFirst() fast on a LinkedList? Yes. It runs in constant time, because the list keeps a direct link to its first node. No elements need to be shifted.
What is the difference between addFirst() and push()? None in effect. push() calls addFirst(). Use push when you treat the list as a stack, and addFirst when you treat it as a deque.
Why does List.addFirst() not compile? In Java 8 through 20, the List interface has no addFirst method. Declare the variable as LinkedList or Deque, or use add(0, element).
Can addFirst() add null? Yes, a LinkedList accepts null. An ArrayDeque does not, and it throws a NullPointerException.
About the author Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful
Helpful Share Copy link Suggestion