ArrayList — backed by a dynamic array. LinkedList — backed by a doubly-linked list.
Analogy: ArrayList is like a numbered parking lot — you can drive straight to spot #50 (fast access by index). LinkedList is like a treasure hunt with clues — you have to follow the chain from the beginning to find the 50th item.
ArrayList (java.util.ArrayList):
Object[]).1ArrayList<String> list = new ArrayList<>();23// Adding elements4list.add("Alice"); // O(1) amortized — append at end5list.add("Bob");6list.add(1, "Charlie"); // O(n) — shifts Bob right78// Accessing elements9String first = list.get(0); // O(1) — instant access10String third = list.get(2); // O(1) — instant access1112// Removing elements13list.remove(1); // O(n) — shifts elements to fill gap1415// Searching16list.contains("Alice"); // O(n) — must scan17list.indexOf("Bob"); // O(n) — must scan1819// Pre-sizing for performance20ArrayList<Integer> big = new ArrayList<>(10000); // No resizing needed
LinkedList (java.util.LinkedList):
1LinkedList<String> linked = new LinkedList<>();23// Adding elements4linked.add("Alice"); // O(1) — append at tail5linked.addFirst("Bob"); // O(1) — add at head6linked.addLast("Charlie"); // O(1) — add at tail78// Accessing elements9String first = linked.get(0); // O(n) — must traverse!10String third = linked.get(2); // O(n) — must traverse!1112// Removing elements13linked.removeFirst(); // O(1)14linked.removeLast(); // O(1)1516// Deque operations (stack/queue)17linked.push("item"); // O(1) — push to head (stack)18linked.pop(); // O(1) — pop from head (stack)19linked.offer("item"); // O(1) — add to tail (queue)20linked.poll(); // O(1) — remove from head (queue)
Complexity comparison:
get(index): ArrayList O(1), LinkedList O(n)add(end): Both O(1) amortizedadd(middle): ArrayList O(n), LinkedList O(1) if you have the node, O(n) to find itremove(middle): ArrayList O(n), LinkedList O(1) if you have the node, O(n) to find itcontains(): Both O(n)When to use which:
Common mistake: Choosing LinkedList thinking it's faster for inserts. In reality, ArrayList is almost always faster due to CPU cache locality, and LinkedList uses more memory per element.