LinkedList in Java
Learn LinkedList end operations and indexed traversal costs, plus when ArrayDeque is a better starting point for Java queues and stacks.
Learn LinkedList end operations and indexed traversal costs, plus when ArrayDeque is a better starting point for Java queues and stacks.
LinkedList in Java
LinkedList is a doubly-linked implementation of List and Deque. Each element sits in a node with links to the previous and next nodes. Relinking at a known node or iterator position is constant time, but finding an indexed position takes traversal.
Introduction
LinkedList stores each element in a node with links to its neighbors. Once a node or ListIterator position is known, insertion or removal there takes O(1) relinking. Finding an index first takes O(n) traversal from whichever end is closer. Operations at the head and tail are O(1) because the list keeps references to both ends.
The tradeoff is the node structure: traversal follows links instead of stepping through a backing array, and each node adds allocation and memory overhead. This can make scans less cache-friendly than ArrayList; measure the workload you care about rather than assuming a fixed speed difference. Indexed access is O(n) for LinkedList and O(1) for ArrayList.
For ordinary FIFO or LIFO use, ArrayDeque is usually the simpler starting point. Its API describes it as a resizable-array Deque with amortized constant-time operations and says it is likely faster than LinkedList as a queue. It rejects null; LinkedList remains useful when you need List operations, iterator-positioned edits, or null elements.
When to Use LinkedList
Use LinkedList when:
- You need
Listoperations and will edit through an already-positionedListIterator - You need a list implementation that permits
nullelements - Your operations are at the head and tail and you also need
Listbehavior
Do not use LinkedList when:
- You frequently access or insert by index (use
ArrayListfor indexed access; locating a LinkedList index is O(n)) - You need a plain queue, stack, or deque without
Listoperations ornullsupport (start withArrayDeque) - You scan through elements in order and have not measured a reason to choose a linked structure
- You need thread-safe operations
- Memory is constrained — each node carries two extra pointer fields
Internal Structure
LinkedList uses a static inner Node class with forward and backward pointers:
private static class Node<E> {
E item;
Node<E> next;
Node<E> prev;
}
The list maintains first and last pointers (for O(1) head/tail access) and tracks size.
Mermaid Diagram: LinkedList Node Structure
graph LR
A["Node prev=null<br/>item=A<br/>next=Node B"] --> B["Node prev=Node A<br/>item=B<br/>next=Node C"]
B --> C["Node prev=Node B<br/>item=C<br/>next=null"]
A --> D["null (head)"]
C --> E["null (tail)"]
Failure Scenarios
| Scenario | Cause | Result |
|---|---|---|
NoSuchElementException |
Calling getFirst() / pop() on empty list |
Runtime crash |
ConcurrentModificationException |
Modifying during iteration | Runtime crash |
| Memory overhead | Very large lists with many nodes | OutOfMemoryError from GC pressure |
Trade-Off Table
| Aspect | LinkedList | ArrayList |
|---|---|---|
| Random access | O(n) — traverses from the nearer end | O(1) |
| Insertion at head | O(1) | O(n) — shift elements |
| Insertion at tail | O(1) | O(1) amortized |
| Insertion at middle | O(n) to reach index, then O(1) to relink | O(1) to reach index, then O(n) to shift |
| Edit at a known iterator position | O(1) relinking | O(n) shifting |
| Per-element structure | A node with links to both neighbors | A reference in a backing array |
| Storage layout | Node links; physical placement is unspecified | Reference array; physical placement is unspecified |
| Iterator invalidation | Only on structural changes at that position | Only on structural changes at that position |
Code Snippets
Deque Operations
The snippets using List.of() require Java 9 or later. The LinkedList and ArrayDeque APIs themselves are available from earlier Java releases.
LinkedList implements Deque, so its addFirst()/addLast(), removeFirst()/removeLast(), and getFirst()/getLast() operations are O(1). They use the list’s head and tail references without traversing nodes.
For an ordinary queue, stack, or deque, start with ArrayDeque unless you need List methods or null elements. It is a resizable-array Deque; most basic operations are amortized O(1), and the Java SE API says it is likely faster than LinkedList when used as a queue. ArrayDeque prohibits null, while LinkedList permits it.
removeFirst() and getFirst() throw NoSuchElementException on an empty list. pollFirst() and pollLast() return null instead. The difference matters: use the throwing variants when an empty list is an error condition; use the poll* variants when an empty list is a valid terminal state, like draining a work queue until it is done. The same pattern applies to peek* versus get* for inspection-only access.
push() and pop() are stack-named aliases for addFirst() and removeFirst(). The explicit end methods make queue and deque code easier to read.
Deque<String> queue = new ArrayDeque<>();
queue.addLast("task1"); // enqueue
queue.addLast("task2");
queue.addFirst("urgent"); // push front
String first = queue.removeFirst(); // "urgent" — amortized O(1)
String next = queue.removeFirst(); // "task1" — amortized O(1)
Indexed and Known-Position Edits
The pointer update is O(1) only after the position is known. listIterator(index) must first walk from the nearer end, so reaching an index takes O(n) in the worst case. Once positioned, ListIterator.add() or remove() relinks nodes in O(1).
List<String> items = new LinkedList<>(List.of("a", "b", "c"));
int position = items.size() / 2;
ListIterator<String> cursor = items.listIterator(position); // O(n) worst case from nearer end
cursor.add("between"); // O(1) relink at this position
Removing During Iteration
LinkedList iterators are fail-fast: after an unsupported structural modification, they may throw ConcurrentModificationException. This is best-effort bug detection, not a guarantee and not a concurrency mechanism. The exact checks are implementation details; do not rely on a particular method such as hasNext() detecting a change.
When the iterator supports it, it.remove() removes the last returned element while preserving that iterator’s traversal state. it.add(element) inserts at the cursor position; it.set(element) replaces the last returned element without a structural change. These operations follow the ListIterator contract.
The code below filters even numbers by calling it.remove() through the iterator rather than calling nums.remove(element) from outside the loop. Using listIterator() instead of iterator() is important here because ListIterator combines forward traversal with remove() in a single cursor object — exactly what you need for conditional removal during iteration.
LinkedList<Integer> nums = new LinkedList<>(List.of(1, 2, 3, 4, 5));
ListIterator<Integer> it = nums.listIterator();
while (it.hasNext()) {
if (it.next() % 2 == 0) {
it.remove(); // Supported by this iterator; keeps traversal valid
}
}
// nums = [1, 3, 5]
Calling list.remove(element) from outside the iterator changes the list behind the iterator. The iterator may detect that change and throw, but fail-fast behavior is best-effort. If the iterator supports removal and the decision depends on the current element, use it.remove() as shown above.
Converting to Array
toArray() copies LinkedList elements into an array. The method comes in two forms: toArray() returns Object[] (requires casting), while toArray(T[] a) returns a typed array. The typed form is what you want in practice.
LinkedList<String> items = new LinkedList<>(List.of("a", "b", "c"));
String[] array = items.toArray(new String[0]); // Zero-length array triggers the grow path
The zero-length array pattern is worth understanding. When you pass an array that is too small, toArray() allocates a new array of the correct type and size. This means the returned array is always a freshly allocated one — your original array is never filled in. Passing an empty array avoids wasting space on an array that will be discarded anyway. If you already know the size, passing a pre-sized array is slightly more efficient because it skips the allocation step:
String[] preSized = items.toArray(new String[items.size()]); // Reuses your array
A few edge cases to keep in mind:
- Null elements: If the list contains
null, it appears asnullin the resulting array. The array is not sparse — it has a value at every index. - Empty list:
toArray(new String[0])returns a newly allocated zero-length array, not your empty array. - Mixed generic types: If the list holds mixed types that do not all extend
T,ArrayStoreExceptionis thrown at runtime.
For most cases, items.toArray(new String[0]) is the idiomatic choice.
Observability Checklist
- Track
LinkedListsize to detect unbounded growth - Monitor iteration time in hot paths — O(n) scans are often misidentified as slow network calls
- Profile memory usage if it matters — each element has a node object and two links, but the byte cost depends on the JVM, object layout, and configuration
- Check for repeated
list.size() == 0checks in loops — consider explicitisEmpty()for clarity - Monitor GC frequency for large linked lists — nodes are individually garbage-collectable unlike array padding
Security Notes
LinkedListis not thread-safe; useConcurrentLinkedDequefor concurrent access- Serializing a
LinkedListcan be expensive — each node is serialized independently - Avoid storing sensitive data in nodes that may persist in memory after the list is cleared; unlike arrays, there is no efficient way to zero out node contents
Common Pitfalls / Anti-Patterns
- Assuming O(1) indexed insertion: Relinking is O(1) when you already have the node or an iterator at the position. Finding an index with
listIterator(index)takes O(n) traversal from the nearer end. - Memory overhead: A
LinkedListof 1 millionIntegerobjects requires ~48MB (3 pointers + object header per node) vs ~4MB for anArrayListof the same elements. - Reverse iteration: Use
list descendingIterator()for efficient tail-to-head traversal pollFirst()vsremoveFirst():pollFirst()returnsnullon empty list;removeFirst()throwsNoSuchElementExceptionaddFirst()vspush(): Both insert at the head;push()is the stack-named alias foraddFirst().
Quick Recap
LinkedListhas O(1) operations at the head and tail; edits at an already-known node or iterator position are also O(1)- Reaching an index with
listIterator(index)takes O(n) traversal from the nearer end - Random access is O(n) — do not use LinkedList when index-based access is frequent
- Implements both
ListandDeque; for ordinary queue or stack use, start withArrayDequeunless you needListmethods ornullelements - Each node stores two pointers in addition to the value — higher memory overhead than ArrayList
- Linked traversal may have worse locality than an array-backed list; measure sequential scans for your workload
Interview Questions
Further Reading
- Java SE 27
LinkedListAPI — indexed traversal and list/deque operations - Java SE 27
ArrayDequeAPI — resizable-array deque, amortized operation costs, and null restrictions - Baeldung: LinkedList vs ArrayList — Detailed performance comparison with benchmarks
- How LinkedList Works Internally — Step-by-step explanation of node structure and operations
- When to Use LinkedList — Use cases where LinkedList outperforms ArrayList
- ArrayList — resizable array, the most common List implementation
- Queue and Deque — Queue interface implemented by LinkedList
- HashMap — hash-based maps with different performance tradeoffs
Conclusion
LinkedList has O(1) operations at the head and tail. Insertion or removal is also O(1) once the node or ListIterator position is known; finding an indexed position takes O(n) traversal from the nearer end. This is why indexed insertion is not automatically constant time.
For List workloads, choose based on access pattern: ArrayList suits frequent indexed access, while LinkedList can fit when edits happen through an already-positioned iterator or when the list must permit null. For ordinary FIFO or LIFO behavior, ArrayDeque is the usual starting point. Its basic operations are amortized O(1), it prohibits null, and the Java SE API says it is likely faster than LinkedList as a queue.
See Queue and Deque for the queue interfaces and TreeSet for ordered unique collections.
Category
Related Posts
Abstract Classes in Java: Interfaces and Composition
Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.
Arithmetic Operators in Java: Division, Overflow, Promotion
Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.
Java Array Basics: Length, Bounds, Copies, and Resizing
Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.