Which structure, which collection
Every structure in an algorithms course is in java.util under another name. The map, and the two rows people get wrong.
Textbook data structures and java.util are the same subject taught twice, and most people learn them separately — the structures in an algorithms course, the collections at work — and never quite join them up.
This lesson is the join. Everything below is covered in depth by the collections course; what is here is which is which, and how to choose.
The map
| The structure | What Java calls it | The operation it is good at | Cost |
|---|---|---|---|
| dynamic array | ArrayList | index, append | O(1) both, amortised |
| doubly linked list | LinkedList | insert/remove at an end | O(1) — but O(n) to reach an index |
| hash table | HashMap, HashSet | lookup by key | O(1) average |
| balanced BST (red-black) | TreeMap, TreeSet | lookup in order, ranges | O(log n) |
| ring buffer | ArrayDeque | push/pop at both ends | O(1) |
| binary heap | PriorityQueue | "give me the smallest" | O(log n) |
| insertion-ordered hash | LinkedHashMap | lookup, plus a stable order | O(1) |
Two rows in that table are the ones people get wrong, and both are about reaching an element rather than changing it.
LinkedList is O(1) at the ends and nowhere else
The textbook says linked lists are good at insertion. Measured three ways on 200,000 elements:
### 1. insert at the FRONT
### ArrayList 1844 ms
### LinkedList 5 ms
### 2. insert in the MIDDLE, by index
### ArrayList 24 ms
### LinkedList 429 ms
### 3. walk the whole list by index, get(i)
### ArrayList 1 ms
### LinkedList 3252 msThe textbook is right about the first and wrong about the second, which is the case people usually mean.
Inserting into a linked list is O(1) once you are holding the node. add(index, e) is not holding the node — it walks there first, which is O(n). So the advertised O(1) applies at the head, at the tail, and through an Iterator you already have, and nowhere else.
The third row is the same fact and the reason LinkedList is almost never the right choice in practice: get(i) in a loop is O(n²) overall, and the elements are scattered across the heap rather than contiguous, so every step is a cache miss. ArrayList wins by three thousand times at a task the two structures are supposedly comparable at.
Hash or tree: the question is whether you need order
HashMap and TreeMap both map keys to values. The choice is not performance, it is what you need besides lookup:
HashMap— O(1) average, no order at all. Iteration order is not a contract and has changed between Java versions.TreeMap— O(log n), kept sorted, and that buys you operations a hash cannot do at any price:firstKey,lastKey,headMap,tailMap,subMap,floorKey,ceilingKey.
So: "every order between £100 and £500" is a TreeMap question. "the order with this id" is a HashMap question. If you find yourself sorting a HashMap's entries on every request, you wanted a TreeMap.
And LinkedHashMap is the third answer people forget: hash lookup, plus iteration in insertion order (or access order, which is how you build an LRU cache in about six lines).
The heap is a priority queue, not a sorted list
PriorityQueue keeps the smallest element at the head and everything else only loosely arranged. That distinction has one consequence that surprises everybody exactly once:
Iterating a PriorityQueue does not give you sorted order. Only poll() does, one element at a time. A for (T t : queue) walks the backing array, which is heap-ordered, not sorted.
What it is for: "the k largest of a very large stream". Keep a heap of size k, push, and drop the smallest when it grows past k — O(n log k) and O(k) memory, where sorting everything is O(n log n) and O(n) memory. On a hundred million elements that is the difference between running and not.
Choosing, as a sequence of questions
- Do I look things up by key? →
HashMap. Unless I also need order →TreeMap. - Do I need to know whether I have seen something? →
HashSet. This is the single most valuable swap in ordinary code, and the big-O lesson measured it:List.containsin a loop was 1,900× slower at 100,000 elements. - Is it a list I index? →
ArrayList, pre-sized if I know the size. - Do I add and remove at the ends? →
ArrayDeque, for both stack and queue. - Do I repeatedly need the smallest or largest? →
PriorityQueue. - Do I need insertion order and fast lookup? →
LinkedHashMap.
What has no collection, and why
Two structures in this course have no java.util equivalent, and that is the reason they get their own lessons:
- Tries — nothing in the standard library does prefix search. A
TreeMapgets close withsubMap, and a trie is the structure the problem actually wants. - Graphs — Java has no graph type at all. You build one from the collections above, and which ones you choose is the first real decision in any graph problem.
Under the hood: what "O(1) average" for HashMap actually is, and what ArrayDeque actually does at each end
HashMap is an array of buckets, sized to a power of two, and a key's bucket is hash(key) & (capacity - 1) — a mask, not a modulo, which is exactly why capacity is always a power of two. Each bucket used to be a linked list of entries that hashed there; get and put are O(1) only because a well-spread hash keeps each bucket to roughly one entry. A pathological key set (or a broken hashCode() that returns a constant) collapses every key into one bucket, and lookup there degrades to a linked-list scan — genuinely O(n).
Since Java 8, a bucket that grows past a threshold (eight entries, with the table at least 64 slots) treeifies: the linked list becomes a small red-black tree, and worst-case lookup in that one bucket becomes O(log n) instead of O(n). That single change is why the which-structure table above can honestly say "O(1) average" without a matching "O(n) worst case" caveat needing to dominate the conversation — the treeify threshold exists specifically to bound how bad a bad day can get. It also means hashCode() quality is not a style nitpick: a map of keys with the same (or clustered) hash gets its buckets treeified far more often, trading the map's O(1) promise for a real, if bounded, cost on every affected key.
ArrayDeque is a circular buffer over a plain array, with a head and tail index that wrap around using the same power-of-two-mask trick HashMap uses for bucket indices. Pushing at either end is writing one slot and moving that end's index by one, wrapping to zero when it runs off the array — no shifting of the other elements, which is exactly why both ends are O(1) and why it outperforms LinkedList even at the ends it is supposedly tied with: one array write beats allocating a node object and updating two pointers. When the buffer fills, it doubles and copies, the same amortised-growth argument ArrayList makes.
Try it yourself
Reason through a treeified bucket
A HashMap<String, V> has 10,000 entries spread across a table of 16,384 buckets (its capacity after growing to keep the load factor under 0.75), with hashes that spread evenly — except for 50 keys that all happen to hash into the same bucket. What is the practical cost of get() on one of those 50 keys once the bucket has treeified, compared to a key in an ordinary, roughly-one-entry bucket?
Why treeification bounds the damage without eliminating it
An ordinary bucket lookup is close to O(1): one array index to find the bucket, then a scan of roughly one entry. The 50-key bucket, once it treeifies (any bucket reaching 8 entries in a table of at least 64 slots does), becomes a small red-black tree, so lookup there costs O(log 50) ≈ 6 comparisons instead of a linear scan of up to 50 — bounded and still fast in absolute terms, but a real, measurable multiple of the ordinary bucket's cost, and it is paying for extra compareTo-style tree-balancing work on every insert into that bucket too. The deeper lesson is that treeification is a safety net, not a fix: it turns "an attacker who controls keys and a weak hashCode() can make your map O(n)" into "at worst O(log n)", but a hashCode() that clusters keys is still a real cost compared to one that spreads them, even after the net catches it.
Misconceptions
- "A
HashMap's buckets are always linked lists." Only below the treeify threshold. A bucket with 8 or more entries (in a large enough table) becomes a small red-black tree, which is why a hostile or badly-hashed key set degrades to O(log n) per bucket rather than true O(n) — bounded damage, not linear damage. - "
ArrayDequemust be slower thanLinkedListat the ends, since aLinkedListis 'built for' insertion there." The opposite:ArrayDeque's circular-buffer write is one array store and an index update, with no node allocation and no pointer chasing, which is why it beatsLinkedListeven at the operationLinkedListis supposedly optimised for.
Sources
- Joshua Bloch, Effective Java (3rd ed.) — collection implementation choice,
hashCode()/equals()contracts, and why they matter toHashMapperformance. - OpenJDK
java.util.HashMapsource and its class-level Javadoc — bucket structure, the treeify threshold, and load factor. - OpenJDK
java.util.ArrayDequesource and its class-level Javadoc — the circular-array implementation and its stated complexity guarantees.