Codectionary / Developer documentation / Java

LinkedList

LinkedList is a doubly-linked list implementation of both the List and Deque interfaces. Unlike ArrayList, it stores elements as individual nodes linked to their neighbors, which makes inserting and removing elements at the beginning or middle much faster, at the cost of slower random access by index. Because it implements Deque, LinkedList can also be used directly as a stack or queue.

Syntax

LinkedList<Type> list = new LinkedList<>();

Examples

Basic LinkedList Usage

LinkedList supports the same core List operations as ArrayList.

import java.util.LinkedList;

LinkedList<String> tasks = new LinkedList<>();
tasks.add("Write code");
tasks.add("Test code");
tasks.add("Deploy code");

System.out.println(tasks);       // [Write code, Test code, Deploy code]
System.out.println(tasks.get(1)); // Test code

Fast Insertion at Both Ends

LinkedList excels at adding or removing from the front or back, unlike ArrayList.

import java.util.LinkedList;

LinkedList<Integer> list = new LinkedList<>();
list.add(2);
list.add(3);

list.addFirst(1);  // fast - O(1)
list.addLast(4);    // fast - O(1)

System.out.println(list);  // [1, 2, 3, 4]

list.removeFirst();
System.out.println(list);  // [2, 3, 4]

Using LinkedList as a Stack

LinkedList's Deque interface provides push/pop for stack-like (last-in-first-out) behavior.

import java.util.LinkedList;

LinkedList<String> stack = new LinkedList<>();
stack.push("first");
stack.push("second");
stack.push("third");

System.out.println(stack.pop());  // third (last one pushed, comes off first)
System.out.println(stack.pop());  // second
System.out.println(stack);         // [first]

Using LinkedList as a Queue

LinkedList's Queue methods provide first-in-first-out behavior.

import java.util.LinkedList;
import java.util.Queue;

Queue<String> queue = new LinkedList<>();
queue.offer("first");
queue.offer("second");
queue.offer("third");

System.out.println(queue.poll());  // first (first one added, comes off first)
System.out.println(queue.peek());   // second (look without removing)

Best practices

  • Choose LinkedList over ArrayList when your code frequently inserts or removes elements at the beginning or middle of the list
  • Choose ArrayList instead when you mostly need fast random access by index - LinkedList access by index is slow (O(n)) since it must walk the chain
  • Use LinkedList's Deque methods (push/pop, offer/poll) when you specifically need stack or queue behavior, rather than reimplementing that logic yourself
  • Consider ArrayDeque instead of LinkedList for pure stack/queue use cases - it is generally faster and more memory-efficient

Runtime & versions

Java Virtual Machine. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

Java Language Specification

Specifications & further reading