The Analogy: The Coupled Wagons In A Shunting Yard
A freight train in a marshalling yard is not a numbered rack. Each wagon knows two things: the wagon coupled in front of it and the wagon coupled behind it. Nothing knows the whole train. There is no board at the yard entrance listing wagon one, wagon two, wagon three; there are couplings, and a coupling only tells you about its immediate neighbour. If the foreman wants the eleventh wagon, somebody walks the train, counting.
That arrangement is brilliant at the two things it is brilliant at. Adding a wagon to either end is one coupling and takes seconds -- no other wagon moves, no other wagon even notices. Removing a wagon from the middle is two uncouplings and one new coupling, and again nothing else moves, which is exactly the operation that a solid rack of bolted-down bays makes impossible. But the saving only exists if the shunter is already standing at the right coupling. If he has to walk from the locomotive to find the spot first, the walk is the whole cost and the clever coupling is a rounding error.
The other thing about a train in a yard is that it is not one continuous run of track. Wagons get shuffled into whichever siding had room, so walking the train means walking all over the yard, and each step costs a walk to somewhere new rather than a step sideways. A rack of numbered bays, by contrast, is one continuous run: the storeman's eye and his feet both go in a straight line. Each wagon also carries its own couplings, its own chalked number and its own paperwork, so the per-wagon overhead is real -- a hundred wagons is a hundred sets of couplings, where a hundred numbered bays is one painted line and a hundred chalk marks.
Then the yard office writes a computer system, and the clipboard it replaces had wagons numbered one to eleven, so the system asks for "wagon 11" as a matter of course. Every request sends a shunter walking from the locomotive. A job that touches every wagon in turn -- checking each one against every other for a duplicate consignment number, say -- now sends a shunter walking the train twice for every pair, and the number of pairs grows with the square of the train. On a six-wagon train nobody notices. On a six-hundred-wagon train the yard grinds to a halt, and the report says the software is slow, and every individual operation in it is exactly as fast as it was designed to be. Nothing broke. The office simply asked a chain of couplings to behave like a numbered rack.
Syntax or Core Structure
LinkedList is a doubly-linked list. It implements List, so it has indexes, and it implements Deque, so it has both ends.
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
public class ShuntingYard {
public static void main(String[] args) {
LinkedList<String> train = new LinkedList<>();
train.add("hopper"); // List: append at the tail
train.add("tanker");
train.addFirst("loco"); // Deque: constant time at the head
train.addLast("brake-van"); // Deque: constant time at the tail
train.add(2, "flat"); // List: walks to index 2 before relinking
System.out.println("size " + train.size());
System.out.println("train " + train);
System.out.println("head " + train.getFirst());
System.out.println("tail " + train.getLast());
System.out.println("index 2 " + train.get(2));
System.out.println("find " + train.indexOf("tanker"));
String pulled = train.removeFirst();
System.out.println("pulled " + pulled);
System.out.println("now " + train);
List<String> asList = train; // it is a List
Deque<String> asDeque = train; // and it is a Deque
System.out.println("both " + (asList.size() == asDeque.size()));
}
}
Output:
size 5
train [loco, hopper, flat, tanker, brake-van]
head loco
tail brake-van
index 2 flat
find 3
pulled loco
now [hopper, flat, tanker, brake-van]
both true
Every line there is cheap except two. addFirst, addLast and removeFirst touch one or two couplings and nothing else, which is the whole reason this class exists. get(2) and add(2, "flat") had to walk to position two first, and indexOf("tanker") had to walk until it found a match. The last line is the fact that makes LinkedList unusual in the JDK: the same object answers to List and to Deque, so one variable can be an indexed sequence and a double-ended queue at once. Whether you want that is a different question.
Technical Depth: What A Node Costs, Which Operations Are Genuinely Constant, And Why ArrayList Usually Wins Anyway
The node, and what one element really costs
Every element in a LinkedList is wrapped in a private Node object holding three fields: the item, the next node and the previous node. Every element in an ArrayList is one slot in one Object[].
| Aspect | ArrayList | LinkedList |
|---|---|---|
| Storage per element | one reference slot in a shared array | a Node object with an item, a next and a prev |
| Memory locality | contiguous, so a walk reads cache lines in order | nodes sit wherever the allocator put them |
get(int) | constant, one index calculation | walks from whichever end is nearer |
| Add at the tail | amortised constant, with an occasional array copy | constant, one relink |
| Add or remove at the head | linear, every element shifts | constant |
| Add or remove in the middle | linear, but a single System.arraycopy | linear walk, then constant relink |
| Marker interfaces | RandomAccess | Deque and Queue |
The get(int) row is more precise than "linear": the JDK checks whether the index is in the first or second half and walks forward from the head or backward from the tail accordingly. That halves the average walk and changes nothing about the shape of the cost.
The locality row is the one that decides real benchmarks and the one that no complexity table shows. A pointer walk through nodes scattered across the heap misses cache on most hops, and a cache miss costs roughly as much as a hundred arithmetic operations. ArrayList's "expensive" middle insert is System.arraycopy, which moves memory at bus speed. That is why the class with the worse asymptotic bound wins the measurement so often.
The trap: an index in a loop
The cost of get(i) is invisible at the call site, so the mistake writes itself. This program counts the hops instead of timing them, so the numbers are exact rather than machine-dependent.
public class Walks {
static final class Node {
String item;
Node next;
Node(String item) { this.item = item; }
}
static int hops = 0;
static Node at(Node head, int index) {
Node n = head;
for (int i = 0; i < index; i++) {
n = n.next;
hops++;
}
return n;
}
public static void main(String[] args) {
Node head = new Node("w0");
Node tail = head;
for (int i = 1; i < 8; i++) {
Node n = new Node("w" + i);
tail.next = n;
tail = n;
}
hops = 0;
for (int i = 0; i < 8; i++) {
at(head, i); // the indexed loop
}
System.out.println("indexed " + hops);
hops = 0;
Node n = head;
while (n != null) { // the walk
n = n.next;
hops++;
}
System.out.println("walked " + hops);
System.out.println("eighth " + at(head, 7).item);
}
}
Output:
indexed 28
walked 8
eighth w7
Eight elements, and the indexed loop cost 28 hops against the walk's 8, because visiting index i costs i hops and the total is the sum from zero to seven. That sum is n(n-1)/2, so the gap widens fast: at a thousand elements the walk still costs a thousand hops and the indexed loop costs 499,500. Nothing in the source of the indexed loop looks quadratic. The fix is not a clever one -- write for (String s : list), which compiles to exactly the single walk, and reach for ListIterator when you need the position as well as the element.
The operations that really are constant, and the iterator that unlocks them
list.add(i, x) is advertised as a cheap insert and is not, because the walk to i dominates. ListIterator.add and ListIterator.remove are the cheap ones, because the iterator is already standing at the node.
import java.util.LinkedList;
import java.util.ListIterator;
public class Middle {
public static void main(String[] args) {
LinkedList<String> train = new LinkedList<>();
train.add("a");
train.add("b");
train.add("c");
train.add("d");
ListIterator<String> it = train.listIterator();
while (it.hasNext()) {
String w = it.next();
if (w.equals("b")) {
it.add("b2"); // goes in behind b, and next() will not return it
}
if (w.equals("c")) {
it.remove(); // removes the element next() just returned
}
}
System.out.println("after " + train);
System.out.println("size " + train.size());
ListIterator<String> back = train.listIterator(train.size());
StringBuilder sb = new StringBuilder();
while (back.hasPrevious()) {
sb.append(back.previous());
}
System.out.println("reversed " + sb);
}
}
Output:
after [a, b, b2, d]
size 4
reversed db2ba
Two details in that trace are worth holding on to. it.add("b2") inserted the element behind the cursor, so the following next() returned c rather than b2 -- an iterator that inserts will not immediately revisit what it inserted, which is what stops the loop running away. And add clears the iterator's memory of the last returned element, so an it.remove() straight after an it.add() throws IllegalStateException; the two guards in this loop are deliberately on different elements. The backwards walk shows the other half of "doubly linked": hasPrevious and previous are as cheap as their forward counterparts, and descendingIterator() from Deque does the same job in one call.
The Deque face, and the three method families that mean the same thing
Because LinkedList implements Deque, it inherits three parallel sets of names for the same handful of operations. They differ in what they do when the collection is empty.
| Intent | Throws when empty | Returns a sentinel when empty | End-specific Deque name |
|---|---|---|---|
| Insert at the tail | add | offer | addLast or offerLast |
| Remove from the head | remove | poll | removeFirst or pollFirst |
| Look at the head | element | peek | getFirst or peekFirst |
Pick a column and stay in it. Mixing poll with removeFirst in one class means half the code handles empty by checking for null and half handles it by catching NoSuchElementException, and the reader has to work out which half they are in.
Two Deque methods carry a surprise. push and pop are stack operations, and on a Deque they both work on the head -- push is addFirst and pop is removeFirst. The legacy java.util.Stack pushes onto the tail of its backing vector, so code moved from Stack to Deque keeps working only because both are consistent with themselves; anything that mixed indexed access with push will silently reverse.
The other surprise is that LinkedList permits null elements. That makes the sentinel column ambiguous: poll() returning null means either "the queue was empty" or "the head really was null", and there is no way to tell after the fact. ArrayDeque forbids null precisely so that poll and peek can be trusted, which is both a reason to prefer it and the one reason you might be stuck with LinkedList.
Why ArrayList and ArrayDeque usually win
The honest summary is that LinkedList is a class with a narrow niche and a wide reputation. Its advantages need you to already hold the position, and almost no real code does -- it holds an index, which is the one thing a linked list cannot use.
For queue and stack work, ArrayDeque is the JDK's own recommendation: a circular array with no per-element node, so it beats LinkedList on both memory and speed at every end operation. For indexed work, ArrayList wins for the reasons in the first table. That leaves three cases where LinkedList is genuinely the right answer: you hold ListIterators across many edits and splice heavily; you need one object that is both a List and a Deque; or you must store null in a double-ended queue, which ArrayDeque refuses.
One more cost is easy to miss. Sorting a LinkedList does not sort it in place -- Collections.sort and List.sort copy the elements into an array, sort the array, and write them back through a ListIterator. That is the right implementation, and it means a sort allocates a full second copy of the list.
Fail-fast iteration, and what a caught ConcurrentModificationException leaves behind
A LinkedList keeps a modCount that increments on every structural change. Its iterators record that count when they are created and compare it on next(), throwing ConcurrentModificationException if it has moved. This is a bug detector, not a lock: it is documented as best-effort, and hasNext() does not check it, so a removal of the second-to-last element can end the loop early instead of throwing.
The important consequence is what a caught ConcurrentModificationException means. The modification that upset the iterator already happened -- the element really was removed -- so catching the exception and continuing leaves you holding a collection that is half-way through a change nobody designed. Treat it the way you would treat an assertion failure. The only safe way to remove during iteration is Iterator.remove, which updates the expected count as it goes, or removeIf, which does the same thing behind one call.
None of this is thread safety. LinkedList is unsynchronised; Collections.synchronizedList locks the individual method calls but not a traversal, so you must hold the wrapper's monitor for the whole loop. There is no concurrent linked list in the JDK -- ConcurrentLinkedQueue and ConcurrentLinkedDeque cover the queue shapes, and CopyOnWriteArrayList covers the read-mostly list shape.
Real World Example: A Wagon Register That Was Written With Indexes And A Queue That Could Not Tell Empty From Null
import java.util.ConcurrentModificationException;
import java.util.Deque;
import java.util.Iterator;
import java.util.LinkedList;
public class MarshallingYard {
private final LinkedList<String> order = new LinkedList<>();
private int getCalls = 0;
private long nodeHops = 0;
void append(String wagon) {
order.addLast(wagon); // constant time: this part is fine
}
// Models one indexed access. The JDK walks from whichever end is nearer,
// which is what Math.min encodes here.
String at(int i) {
getCalls++;
nodeHops += Math.min(i, order.size() - 1 - i);
return order.get(i);
}
int countDuplicatePairs() { // the quadratic scan, written the obvious way
int pairs = 0;
for (int i = 0; i < order.size(); i++) {
for (int j = i + 1; j < order.size(); j++) {
if (at(i).equals(at(j))) {
pairs++;
}
}
}
return pairs;
}
public static void main(String[] args) {
MarshallingYard yard = new MarshallingYard();
for (String w : new String[] { "w1", "w2", "w3", "w2", "w4", "w5", "w3", "w6" }) {
yard.append(w);
}
int pairs = yard.countDuplicatePairs();
System.out.println("wagons " + yard.order.size());
System.out.println("pairs " + pairs);
System.out.println("get calls " + yard.getCalls);
System.out.println("node hops " + yard.nodeHops);
int hops = 0;
for (String w : yard.order) { // the same data, walked once
if (w != null) {
hops++;
}
}
System.out.println("foreach " + hops);
Deque<String> shunt = new LinkedList<>();
shunt.push("A"); // push is addFirst: it works on the HEAD
shunt.push("B");
shunt.addLast("C");
System.out.println("deque " + shunt);
System.out.println("pop " + shunt.pop());
System.out.println("left " + shunt);
LinkedList<String> withNull = new LinkedList<>();
withNull.add(null); // LinkedList permits this
LinkedList<String> empty = new LinkedList<>();
System.out.println("sizes " + withNull.size() + " " + empty.size());
System.out.println("poll one " + withNull.poll());
System.out.println("poll none " + empty.poll());
boolean threw;
try {
for (String w : yard.order) {
if (w.equals("w4")) {
yard.order.remove(w); // structural change during iteration
}
}
threw = false;
} catch (ConcurrentModificationException ex) {
threw = true;
}
System.out.println("threw " + threw);
System.out.println("after cme " + yard.order.size());
int removed = 0;
Iterator<String> it = yard.order.iterator();
while (it.hasNext()) {
if (it.next().equals("w3")) {
it.remove(); // the sanctioned way
removed++;
}
}
System.out.println("removed " + removed);
System.out.println("final " + yard.order);
}
}
Output:
wagons 8
pairs 2
get calls 56
node hops 84
foreach 8
deque [B, A, C]
pop B
left [A, C]
sizes 1 0
poll one null
poll none null
threw true
after cme 7
removed 2
final [w1, w2, w2, w5, w6]
The parts of this class that use LinkedList as a linked list are correct and cheap. append is addLast, which touches one coupling regardless of how long the train is. The deque section performs three end operations and a pop without walking anything. And the final removal loop deletes both duplicate wagons through Iterator.remove, which is constant time per removal once the iterator is standing there -- that single pass is the operation a linked list genuinely beats an array at.
Then read the four numbers at the top. Eight wagons produced 56 indexed accesses costing 84 node hops, against a single for-each that visited all eight in eight steps. The ratio is not the problem; the growth is. countDuplicatePairs makes n(n-1) indexed calls and each one walks, so a train of a thousand wagons makes 999,000 calls costing about 249 million hops, while the for-each still costs a thousand. And the get calls figure is not even the real bill -- each hop is a jump to wherever the allocator put the next node, so the cache misses that no counter here records are what actually shows up in the timings.
The two queue lines are the second bug, and they are quieter. push put A and then B on the head, so the deque reads B, A, C and pop returned B -- correct for a Deque, and the opposite of what somebody arriving from java.util.Stack expects, because that class pushes onto the tail. Below it, two poll() calls print an identical null: one list held a single null element and the other was empty. The sizes line is the only thing in that output that can tell them apart, and it had to be printed before the polls to be any use. This is the ambiguity ArrayDeque removes by forbidding null outright.
The remaining limits are worth stating plainly. The ConcurrentModificationException was caught, but w4 was really gone before the exception was thrown -- after cme reads 7 -- so the catch block is holding a collection that is half-way through an edit nobody planned; a caught ConcurrentModificationException should end the operation, not be swallowed. getCalls and nodeHops are instance fields that are never reset, so calling countDuplicatePairs twice double-counts and any report built from them is wrong. at models the walk but not the cache, so its numbers are a lower bound on the real cost rather than a measurement. order is a LinkedList field rather than a List, so every method in the class can reach for get(i) again, and the class publishes no accessor that would let it be swapped for an ArrayList. And the whole duplicate scan is the wrong algorithm regardless of the list: one pass adding each wagon to a HashSet finds the same duplicates in linear time, and would have made the choice of list irrelevant.
Common Mistakes
- Indexing a
LinkedListin a loop.for (int i = 0; i < list.size(); i++) list.get(i)
walks from an end on every iteration, so a single pass costs n(n-1)/2 hops instead of n. Nothing at the call site looks quadratic. Use a for-each or a ListIterator.
- Believing "insert in the middle is constant time" without holding the position.
list.add(i, x) is a walk followed by a relink, so it is linear. Only ListIterator.add and ListIterator.remove are constant, because the iterator is already at the node.
- Choosing
LinkedListfor queue or stack work.ArrayDequeis a circular array with no
per-element node, and it is faster and smaller at every end operation. The JDK's own documentation points you at it.
- Treating a null from
pollorpeekas "empty".LinkedListpermits null elements, so
null means either an empty queue or a null head and nothing distinguishes them. Check isEmpty(), or use ArrayDeque, which forbids null so that the sentinel is unambiguous.
- Expecting
pushandpopto work on the tail. On aDequethey areaddFirstand
removeFirst, operating on the head. The legacy java.util.Stack pushes onto the tail, so code that mixes indexed access with push reverses when it is ported.
- Modifying the list during a for-each. Any structural change invalidates the iterator, and
next() throws ConcurrentModificationException. Worse than the throw is catching it and carrying on: the modification already happened, so you are holding a half-edited collection.
- Assuming
Collections.synchronizedListmakes iteration safe. It synchronises individual
calls, not traversals; a loop must hold the wrapper's monitor throughout. For genuinely concurrent access use ConcurrentLinkedQueue, ConcurrentLinkedDeque or CopyOnWriteArrayList.
- Underestimating the memory. Each element carries an object header and three references
instead of one array slot, so a LinkedList of a million boxed integers is several times the footprint of an ArrayList of the same and an order of magnitude past an int[]. The nodes are also scattered, which costs cache misses that no complexity table mentions.
- Using a
LinkedListas a lookup structure.contains,indexOfandremove(Object)are
all linear scans. If the question is "is this in there", the answer is a HashSet, and no choice of list will fix a quadratic algorithm.
Best Practices
- Default to
ArrayList, and justifyLinkedListwith a measurement. Contiguous storage
wins the benchmarks so often that the burden of proof belongs on the linked list, not on the array.
- Use
ArrayDequefor anything queue-shaped or stack-shaped. ReserveLinkedListfor the
three cases that need it: heavy splicing through held iterators, one object that must be both a List and a Deque, or a double-ended queue that must accept null.
- Never index a linked list; iterate it. A for-each compiles to exactly one walk, and
ListIterator gives you the position as well as the element when you need both.
- Do positional edits through
ListIterator.addandListIterator.remove. Those are the
operations that make the data structure worth choosing, and they are the ones add(i, x) quietly fails to give you.
- **Declare the variable as
List,QueueorDeque, and say in a comment which costs you are
relying on.** The interface keeps the implementation swappable; the comment stops the next reader from adding a get(i) because the declared type made it look free.
- Stay inside one of the three
Dequemethod families. Choose the throwing set or the
sentinel set for a given class and do not mix them, so every caller handles empty the same way.
- **Remove during iteration only through
Iterator.removeorremoveIf, and treat a caught
ConcurrentModificationException as a corrupted collection.** Fail the operation; do not log it and continue with a list that is part-way through a change.
- Fix the algorithm before the collection. A quadratic scan is quadratic in an
ArrayList
too; a HashSet pass makes the duplicate check linear and the choice of list stop mattering.
Practice Exercises
- The Walk You Paid For. Instrument
countDuplicatePairsas it stands and recordget calls
and node hops for eight, one hundred and one thousand wagons. Then write two more versions: one using a single for-each, and one using a HashSet. Report all three sets of numbers in a small table, reset the counters between runs, and state in two sentences which of the two rewrites mattered more and why the hop counter still understates the real cost.
- The Position You Already Held. Build a list of 100,000 strings and splice 500 new ones into
the middle, four ways: add(i, x) on a LinkedList, ListIterator.add on a LinkedList, add(i, x) on an ArrayList, and ListIterator.add on an ArrayList. Time each with System.nanoTime over several runs and report ratios rather than absolute figures. Explain which of the four is fastest and why the answer is not the one the complexity table predicts.
- The Null That Meant Empty. Put a single null element into a
LinkedListused as a
Deque, then write a method that reports whether the queue is empty using only poll and demonstrate that it cannot be done. Try the same list as an ArrayDeque and record the exact exception and the line that causes it. Finish by writing a small wrapper that forbids null on the way in, and say which of the two fixes you would ship into an existing codebase.