Lesson · Collections Framework
Complexity cheat sheet: what each structure costs
14 min readComplexity Cheat Sheet
One table per family: the cost of every common operation on every implementation, the memory each element carries, and the cases where a plain array scan beats the clever structure.
Asymptotics you can feel
Ten thousand lookups at the middle of a large list. One structure answers instantly; the other replays half its length for every single lookup:
long t0 = System.nanoTime(); for (int i = 0; i < 10_000; i++) { array.get(n / 2); } long t1 = System.nanoTime(); for (int i = 0; i < 10_000; i++) { linked.get(n / 2); } long t2 = System.nanoTime(); System.out.println("ArrayList wins middle lookups: " + (t1 - t0 < t2 - t1)); // true
Predict: why is the difference so large? An array computes the address and reads one slot. A linked list starts at an end and follows half of 200,000 references, ten thousand times: about a billion pointer hops. Big-O is this feeling, written down.
Cost board · green is constant, red is linear
pick a structureMemory: one reference per element, plus up to half spare capacity
The default list: constant time everywhere that does not shift the array.
Reading the colours
Below a few dozen elements the simplest structure wins: scan before hashing, and measure at your real sizes.
Lists
The two list implementations, operation by operation:
| Operation | ArrayList | LinkedList |
|---|---|---|
get(i) / set(i) | O(1) | O(n): the walk from an end |
add at the end | amortised O(1) | O(1) |
add(i, e) / remove(i) | O(n): shifts the tail | O(n): walks, then relinks |
| iterate | O(n), cache friendly | O(n), chasing pointers |
| memory per element | one reference (plus spare capacity) | a node object with three references |
Same big-O, different constants. Both walk in O(n), but one streams through contiguous memory and the other follows indirection. On real hardware that gap is the whole argument for ArrayList as the default.
Sets and maps
Lookup and update across all three flavours of set and map:
| Operation | Hash variants | Linked variants | Tree variants |
|---|---|---|---|
| add / put | O(1) expected | O(1) expected | O(log n) |
| contains / get | O(1) expected | O(1) expected | O(log n) |
| remove | O(1) expected | O(1) expected | O(log n) |
| worst case | O(n) with degenerate collisions | O(n) likewise | O(log n) guaranteed |
| iteration order | none promised | insertion (or access) order | sorted; ranges available |
| memory per entry | entry object, key and value references | entry plus two links | node object with links and a colour bit |
- HashMap degrades gracefully: long collision chains become a tree past a threshold, so the practical worst case is closer to O(log n) than the textbook O(n).
- Hash quality is the hidden input to every O(1): keys with terrible hashCode methods turn the table into a scan, and strings cache theirs after first computation.
Queues and deques
End operations are the product; everything else is inherited from the heap or the ring:
| Operation | ArrayDeque | LinkedList as deque | PriorityQueue |
|---|---|---|---|
| add / offer at either end | O(1) | O(1) | not a deque; O(log n) insertion |
| poll / remove from either end | O(1) | O(1) | O(log n) for the top only |
| peek | O(1) | O(1) | O(1): the smallest is at the head |
| contains | O(n) | O(n) | O(n) |
The heap is not a line. PriorityQueue only promises that the next poll is the smallest; nothing else about the arrangement is sorted, which is why iterating it looks scrambled.
Memory per element, roughly
For 64-bit JVMs, with boxed elements where the type demands them. Treat the numbers as orders of magnitude, not contracts:
| Structure | Per element, roughly | Because |
|---|---|---|
ArrayList | 4 bytes plus growth slack | one compressed reference per slot; capacity overshoots up to half |
ArrayDeque | 4 bytes plus end slack | a circular array of references |
LinkedList | 24 bytes and up | a node object: item, next, previous |
HashMap / HashSet | 32 to 48 bytes | a node with hash, key, value, next; the array of buckets on top |
TreeMap / TreeSet | 40 bytes and up | a node with key, value, left, right, colour, parent |
BitSet | 1 bit | dense range of flags |
Boxing taxes every number. An ArrayList<Integer> of ten thousand small values pays for ten thousand Integer objects before the list itself. An int array or a primitive-aware structure skips that entirely.
When constants beat asymptotics
Where the asymptotic table leaves the decision open:
- Tiny collections: scanning fewer than roughly fifty elements in an array often beats hashing them: no allocation, no hashing, better locality. Most real collections are tiny.
- Locality counts: contiguous memory reaches the CPU cache; pointer chasing misses it. This is why the linked list loses even where both sides are O(1) at the ends.
- Boxing counts: an ArrayList of primitives and an int array are the same big-O and about five times apart in practice.
- Measure at your sizes, not at textbook sizes. The library itself mixes strategies by size, switching small cases to linear paths.
Big-O decides which cases exist; constants decide which case you are in. Use the tables to eliminate the impossible, then measure the two survivors at your real size.
The cost playbook
Using the cheat sheet in review:
- Name the hot operation of the feature, not of the type in general.
- Check that operation's row for the current implementation.
- Scan for accidental O(n): get(i) on a LinkedList, remove(0) on an ArrayList, contains on a Queue.
- Check the memory column when collections are large or numerous; boxed values triple the bill.
- Below a few dozen elements, prefer the simplest structure and stop optimising.
Complexity is a shape, not a score. Match the shape of the data (dense, ordered, keyed) to the shape of the operations (lookup, ends, ranges) and the numbers take care of themselves.
Match the shape, then measure the constants
Array and deque operations are constant at the ends and linear through the middle. Hash variants are constant expected for lookup and pay with no order and memory per entry. Tree variants are O(log n) everywhere and buy sorted ranges. Queues are constant at the ends, heaps are logarithmic per operation. And below a few dozen elements, the simplest structure usually wins: constants and locality decide what big-O leaves open.
Interview angles
Why is LinkedList rarely the right list?+
Its O(1) wins are only at the ends, and ArrayDeque covers those better. Everything index-based is O(n) with pointer chasing, which the array does in one cache-friendly step.
The textbook argument for linked lists assumes cheap pointer moves and expensive shifts; on modern hardware the array's shifts are memmove-fast and its reads are contiguous. Profile evidence usually shows LinkedList as the bottleneck in code that indexes it.
Common misconception: That LinkedList beats ArrayList at inserts in the middle. You must still walk to the middle: O(n) for both, and the array shifts faster than the list walks.
Follow-up: When do you actually keep a LinkedList?
What is the real complexity of HashMap.get?+
O(1) expected: average constant time under a reasonable hash distribution. Worst case O(n) degenerates into a scan, softened by treeifying long chains to around O(log n).
Expected means averaged over hash quality, not over luck. Keys with constant hashCode methods collapse every lookup into one bucket. That is why hash quality is a design input, and why strings cache their computed hash.
Common misconception: That O(1) means one step. It means a constant number of steps on average for real data.
Follow-up: What does TreeMap.get cost, and what does it buy?
A team replaces an ArrayList with a LinkedList for "faster removals". What do you check first?+
Where the removals happen. If they are by index or by value, both types walk to the position: O(n) either way, and the array does it faster. True O(1) removal needs a held iterator node, which is rare outside of queues.
The redesign usually wins by removing the search, not by changing the list: an iterator-based removal pass, a queue at the front, or a Set for membership checks. The data structure change is a symptom fix.
Common misconception: That finer-grained O(1) operations guarantee a faster program. The constants of walking and allocating dominate at typical sizes.
Follow-up: What would removeIf do to this picture?
Where does memory per element actually matter?+
At scale and in multiples: a million boxed Integers in a list pay their object headers first; a map of a million entries pays entry objects plus the bucket array on top. Orders of magnitude change there.
The bill has three parts: references in the structure, node or entry objects, and boxed values. Arrays of primitives skip all three overheads; BitSet skips two. When memory is the constraint, the fix is often an array or a primitive-aware structure, not a different collection.
Common misconception: That memory is the JVM's problem. It is the cache's problem too: bigger footprints mean more cache misses, which is the constant factor from the previous question.
Follow-up: Which structure in the table has the lowest per-element cost?
When does a linear scan beat a hash lookup?+
Small collections, roughly below fifty elements: no hashing, no allocation, contiguous reads, and the branch predictor handles the loop. The library's own code follows the same rule.
This is why micro-optimising a Map for a five-entry configuration is waste, and why the same choice flips at a million entries. The crossover depends on the key type (string hashing and boxed equality cost more than int) and on iteration patterns that amortise over the whole structure.
Common misconception: That asymptotically better is always faster. Asymptotics win at the limit; your data lives somewhere below it.
Follow-up: What single measurement settles the question for a given workload?