Java LinkedList

Beginner
9 min read
Updated: Nov 2026
3 examples
java.util.LinkedList

Definition and Usage

In Java, LinkedList (in java.util, since Java 1.2) stores elements in a chain of doubly linked nodes. Each node holds one element plus two references: one to the previous node and one to the next. The list itself keeps a reference to the first node (the head) and the last node (the tail), so adding or removing at either end never has to move other elements: addFirst(), addLast(), removeFirst(), and removeLast() are all constant-time.

It is unusual because it implements both List and Deque (plus Queue, Cloneable, and Serializable). That means one object can be used as an indexed list with get() and set(), as a queue with offer() and poll(), or as a stack with push() and pop(). A LinkedList keeps elements in insertion order, allows duplicates, and allows null. The LinkedList Methods index lists every guide.

Not thread-safe, and index access is a walk.

A LinkedList is not thread-safe: share it between threads only with your own locking or Collections.synchronizedList(...). Its iterators are fail-fast: structurally changing the list during a loop (other than through iterator().remove()) usually throws ConcurrentModificationException. Also remember that get(i) has to walk node by node, so avoid for (int i...) list.get(i) loops on long lists.

Java Syntax

Import the class, then create a list. The variable type decides which methods you see: List for list work, Queue or Deque for queue and stack work, or LinkedList for all of them:

Java
import java.util.Arrays;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

List<String> names = new LinkedList<>();                          // as a list
Queue<Integer> waiting = new LinkedList<>();                      // as a queue
Deque<String> stack = new LinkedList<>();                         // as a deque or stack
LinkedList<String> copy = new LinkedList<>(Arrays.asList("a", "b")); // [a, b]

names.add("x");                     // [x]
names.add(0, "w");                  // [w, x]
System.out.println(names.get(1));   // x  (index starts at 0)

There is no capacity to choose: a LinkedList allocates one small node per element as it grows, and frees it again when the element is removed. The constructor that takes a collection copies the elements in the order the collection's iterator returns them.

LinkedList vs ArrayList and ArrayDeque

All three keep elements in order, but they are built for different jobs:

TypeGood forKeep in mind
ArrayListReading by index, adding at the end, general-purpose listsInserting or removing near the front shifts every later element
LinkedListOne class that is a List and a Deque; queues that need null; removing while iteratingOne node object per element (more memory); get(i) walks the chain
ArrayDequeQueues and stacks: fast add and remove at both endsNo index access and no null elements

In practice, choose ArrayList for ordinary lists and ArrayDeque for pure queues and stacks. Pick LinkedList when you really need both the List and Deque methods on the same object, or when null elements are part of your data.

What Is Fast and What Is Slow

The chain of nodes makes the ends cheap and the middle expensive to reach:

OperationCostWhy
addFirst(e), addLast(e), add(e)Constant timeOnly a few links are rewired at the head or tail
removeFirst(), removeLast(), poll(), peek()Constant timeThe head and tail are always known
get(i), set(i, e), remove(i)Grows with the distance from the nearer endThe chain is walked from the head or the tail, whichever is closer
contains(o), indexOf(o)Grows with the sizeElements are checked one by one with equals()
listIterator() add / removeConstant once positionedThe iterator already stands on the node, so no search is needed

Queue and Stack Methods: Which One Throws?

Because LinkedList is a Deque, most end operations come in two flavours: one that throws an exception when it cannot work, and one that returns null or false:

JobThrows an exceptionReturns null or false
Insert at the tailadd(e), addLast(e)offer(e), offerLast(e)
Insert at the headaddFirst(e)offerFirst(e)
Remove from the headremove(), removeFirst(), pop()poll(), pollFirst()
Remove from the tailremoveLast()pollLast()
Look without removingelement(), getFirst(), getLast()peek(), peekFirst(), peekLast()

For a queue, add at the tail and take from the head (first in, first out). For a stack, push() and pop() both work at the head (last in, first out). The throwing versions fail with NoSuchElementException on an empty list. Because a LinkedList can contain null, a null from poll() or peek() does not always mean the list was empty; check isEmpty() if you store nulls.

Java Examples

Example 1 — Build a Bus Route with List Methods

Add stops at the front, the end, and the middle, read the ends, search for a stop, and remove stops by value and by index.

Java
import java.util.LinkedList;

public class LinkedListHubRoute {
    public static void main(String[] args) {
        LinkedList<String> stops = new LinkedList<>();
        stops.add("Central");
        stops.add("Park");
        stops.addFirst("Airport");
        stops.addLast("Harbor");
        stops.add(2, "Museum");

        System.out.println(stops + " size=" + stops.size());
        System.out.println("first=" + stops.getFirst() + ", last=" + stops.getLast());
        System.out.println("index of Park: " + stops.indexOf("Park"));

        stops.remove("Museum");
        String removed = stops.remove(1);
        System.out.println("removed " + removed + " -> " + stops);
    }
}

How It Works

  1. Ends and middle. add() appends, addFirst() and addLast() work at the ends, and add(2, "Museum") inserts before the element currently at index 2, so Park and Harbor move one position to the right.
  2. Read and search. getFirst() and getLast() read the ends without removing anything, and indexOf("Park") finds it at index 3.
  3. Two kinds of remove. remove("Museum") removes the first element equal to the value, while remove(1) removes the element at index 1 and returns it: "Central".

Example 2 — Print Queue: offer, peek, and poll

Treat a LinkedList as a first-in, first-out Queue, and compare what poll() and remove() do when the queue is empty.

Java
import java.util.LinkedList;
import java.util.NoSuchElementException;
import java.util.Queue;

public class LinkedListHubQueue {
    public static void main(String[] args) {
        Queue<String> jobs = new LinkedList<>();
        jobs.offer("report.pdf");
        jobs.offer("photo.png");
        jobs.offer("notes.txt");

        System.out.println("next: " + jobs.peek());
        while (!jobs.isEmpty()) {
            System.out.println("printing " + jobs.poll());
        }

        System.out.println("poll on empty: " + jobs.poll());
        try {
            jobs.remove();
        } catch (NoSuchElementException e) {
            System.out.println("remove on empty: NoSuchElementException");
        }
    }
}

How It Works

  1. First in, first out. offer() adds each job at the tail; peek() shows the head without removing it, so the queue still holds all three jobs.
  2. Drain with poll(). Each poll() removes and returns the head, so jobs print in the order they arrived until isEmpty() becomes true.
  3. Two ways to fail. On an empty queue poll() quietly returns null, while remove() throws NoSuchElementException. Pick the style that matches how you want to handle "nothing there".

Example 3 — Browser History as a Stack with push and pop

Use push() and pop() to model a back button, then walk the history from oldest to newest with descendingIterator().

Java
import java.util.Iterator;
import java.util.LinkedList;

public class LinkedListHubStack {
    public static void main(String[] args) {
        LinkedList<String> history = new LinkedList<>();
        history.push("home");
        history.push("search");
        history.push("product");

        System.out.println("history: " + history);
        System.out.println("current page: " + history.peek());

        String left = history.pop();
        System.out.println("left " + left + ", now on " + history.peek());

        Iterator<String> oldestFirst = history.descendingIterator();
        while (oldestFirst.hasNext()) {
            System.out.println("visited: " + oldestFirst.next());
        }
    }
}

How It Works

  1. push() works at the head. Each new page goes to the front, so the list prints newest first: [product, search, home].
  2. Peek and pop. peek() reads the top of the stack without removing it; pop() removes the head and returns "product", leaving search on top.
  3. Reverse walk. descendingIterator() starts at the tail, so the remaining pages come out oldest first: home, then search.

Next: Java LinkedList Methods by Group

Full list with short descriptions: Java LinkedList Methods index (/java/linked-list/method).

Frequently Asked Questions

LinkedList is a class in java.util that stores elements in a chain of doubly linked nodes. It implements both List and Deque, so you can use it as an indexed list, a queue, a double-ended queue, or a stack. It keeps insertion order, allows duplicates, and allows null.
ArrayList keeps elements in one resizable array, so get(i) is instant but inserting or removing near the front shifts elements. LinkedList keeps one node per element, so it adds and removes at either end without shifting, but get(i) must walk the chain from the nearer end. For most lists, ArrayList is the better default.
There is no array to jump into. get(i) starts at the head or the tail, whichever is closer, and follows the links one node at a time, which takes time proportional to the distance. A for loop with get(i) over a LinkedList therefore becomes quadratic; use a for-each loop or an iterator instead.
Only when you need null elements or a List at the same time. For plain queues and stacks, ArrayDeque is usually faster and uses less memory because it stores no node objects. LinkedList works fine for small queues and when you need to remove from the middle with an iterator.
No. Wrap it with Collections.synchronizedList(...) and synchronize manually while iterating, or use ConcurrentLinkedDeque or LinkedBlockingDeque from java.util.concurrent. Its iterators are fail-fast and throw ConcurrentModificationException if the list changes during a loop.

Browse every LinkedList method

Open the methods index for categorized guides with examples and FAQs.

LinkedList Methods Index →

CODETOFUN NEWS

Stay Ahead in Tech

Get the latest IT news, programming updates, and technology trends directly on your phone.

Your daily dose of tech, straight to your feed.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

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