Lesson · Collections Framework
Collections: the architecture behind the names
18 min readCollection Architecture
Java's collections are a hierarchy of contracts — Iterable → Collection → List, Set, Queue, with refinement levels like SortedSet → NavigableSet and Deque, and Map deliberately beside it. Learning the full tree is how you pick the right type in seconds instead of memorising APIs.
Why a hierarchy, not a pile of classes
The collections framework is two trees of interfaces with concrete classes hanging off them. The interfaces describe what a container promises; the classes decide how it is stored and what operations cost.
That split is the whole point. List<String> list = new ArrayList<>() lets every method signature in your code talk about the contract while exactly one line chooses the data structure. Swapping ArrayList for LinkedList later touches that one line — as long as you never relied on implementation-only behaviour.
The hierarchy has grown through default methods, not new trees: forEach, removeIf and stream() were added to Collection years after it shipped, so every existing implementation gained them for free. Interfaces accrete; what you learn about them stays true.
Walking the tree, level by level
Iterable sits at the top of the Collection branch: one method, iterator(), and the reason for-each compiles against anything in the framework.
Collection adds the core verbs every branch shares — add, remove, contains, size, isEmpty — and then the tree splits by shape: List (ordered by position), Set (unique elements), Queue (work taken from an end).
Each branch has its own refinement levels. Set grows a sorted line: SortedSet promises iteration in order and adds first, last, headSet and tailSet; NavigableSet sharpens that with navigation — floor, ceiling, higher, lower, descendingSet. Queue grows Deque, which manages both ends at once: a Deque is equally a stack and a queue.
Map starts a second tree because its unit of work is a key, not an element. Its sorted line mirrors Set's: SortedMap keeps keys in order (firstKey, lastKey, subMap); NavigableMap adds the navigation methods — floorKey, ceilingKey, higherKey, descendingMap.
Both trees end in classes: ArrayList and LinkedList implement List, HashSet and LinkedHashSet implement Set, TreeSet implements NavigableSet, ArrayDeque implements Deque, PriorityQueue implements Queue; HashMap and LinkedHashMap implement Map, TreeMap implements NavigableMap.
| Interface | What it adds | Typical implementation |
|---|---|---|
Iterable | iterator() — the loop machinery behind for-each | everything in the framework |
Collection | add · remove · contains · size · isEmpty | — |
List | position access: get(i), set, indexOf; duplicates allowed | ArrayList, LinkedList |
Set | no duplicates — equals/hashCode decide identity | HashSet, LinkedHashSet |
SortedSet | sorted iteration + ranges: first, last, headSet, tailSet | TreeSet |
NavigableSet | navigation: floor, ceiling, higher, lower, descendingSet | TreeSet |
Queue | take from the head: offer, poll, peek | PriorityQueue |
Deque | both ends: addFirst, pollLast, … — stack and queue in one | ArrayDeque, LinkedList |
Map | key → value; a separate tree, not a Collection | HashMap, LinkedHashMap |
SortedMap | keys in order: firstKey, lastKey, subMap | TreeMap |
NavigableMap | navigation: floorKey, ceilingKey, higherKey, descendingMap | TreeMap |
Read the tree as promises. Every step down adds methods and removes freedom: Collection accepts any implementation; List promises positions; NavigableSet promises to answer "what is the closest element below this one?". Parameter types should promise the least the body needs.
The hierarchy · two trees, drawn in full
click any nodeThe Collection branch
The Map branch — a separate tree on purpose
What it adds
Ordered by position, duplicates allowed: get(i), set(i, e), add(i, e), indexOf. Since Java 21 it is also a SequencedCollection.
Typical implementations
Java 21 slotted the Sequenced interfaces in between — List, Deque, LinkedHashSet, SortedSet, LinkedHashMap and SortedMap gained getFirst / getLast / reversed(); the lesson text walks through them. The Map tree stays separate on purpose: its methods take keys, not elements.
Java 21: the Sequenced interfaces
In Java 21 the hierarchy gained a name for something lists, deques, linked sets and sorted maps always had in common: a clear first end and last end. SequencedCollection extends Collection and gives that idea first-class methods — getFirst, getLast, addFirst, addLast and reversed() — and the existing types were slotted in underneath: List and Deque now extend SequencedCollection, LinkedHashSet and SortedSet extend SequencedSet, LinkedHashMap and SortedMap extend SequencedMap.
The payoff is uniform vocabulary. reversed() used to exist only on NavigableSet and Deque; now every sequenced type has it — as a live view of the original, not a copy:
// the demo's list, holding go / java / java: list.getFirst(); // "go" list.getLast(); // "java" list.reversed(); // [java, java, go] — a view, not a copy
Name what it is: Sequenced is a promise about the ends — every sequenced collection can name its first and last element and run backwards, whatever kind of container it is.
Choosing in three questions
Picking a collection is not a memory game. Three questions settle the branch, in this order — and the picker below answers them for any combination you choose. Thread safety is the bonus question, covered by one extra chip.
- Q1 · What does one slot hold? A single value, or a key → value pair? A pair means a Map and the branch decision is over.
- Q2 · How do you retrieve an item? By position (get(i)) → List. By membership (contains) → Set. Always from an end — FIFO, stack, priority → Queue or Deque.
- Q3 · What order matters? None needed → hash-based, the fastest. Insertion order → the Linked variants. Sorted → the Tree variants, which compare instead of hash.
Find your collection
Step 1 · What does one slot hold?
Bonus · Shared between threads?
Answer the steps above — the recommended type, a construction line and the reason appear here as soon as the path is decided.
Contracts that change behaviour
equals and hashCode decide identity for HashSet and HashMap — two objects that are equal() share a slot, so fields used in equals must never mutate while the object is stored.
Sorted collections (TreeSet, TreeMap) do not hash at all: they compare, using Comparable or a Comparator you supply. Get those two assumptions right and every collection behaves predictably.
- Hash-based — O(1) average, no order promised: HashMap, HashSet.
- Linked variants — insertion order, kept by a list threaded through the entries: LinkedHashMap, LinkedHashSet.
- Tree variants — sorted, plus range queries (floor, ceiling, subMap) at O(log n): TreeMap, TreeSet.
Details interviewers actually drill
Four details separate people who skimmed the docs from people who have actually shipped with these types.
- RandomAccess is a real algorithm switch. ArrayList implements this marker interface; LinkedList doesn't. Generic algorithms read it: Collections.binarySearch uses get(index) hops on RandomAccess lists and an iterator walk otherwise — which is why binary search over a LinkedList degrades from O(log n) comparisons to O(n) hops.
- Iteration is fail-fast by contract. Most iterators track a modification count: structurally change the collection except through the iterator itself, and the next step throws ConcurrentModificationException. It is a single-threaded bug detector, not synchronisation.
- Collection vs Collections. The interface and the toolbelt class. unmodifiableList, synchronizedMap, emptyList, nCopies, shuffle and reverse live in Collections — most "missing methods" are already there.
- Declare the narrowest contract. A method that needs iteration takes Collection; one that needs indexing takes List; one that only needs lookup takes Map. Narrow parameters let more callers pass what they already have.
Map is not a Collection
Map doesn't extend Collection, so you can't pass a Map where a Collection is expected — a compile-time surprise for every newcomer. The bridge is entrySet(): a Map really is a Set of key→value entries, which is why for-each works over map.entrySet() and not over the map itself.
Interview angles
List, Set, Queue, Map — how do you decide quickly?+
One question fixes the shape: look items up by key (Map), by position (List), by membership (Set), or consume from an end (Queue/Deque). A second question picks the implementation: ordering needs first, thread-safety second.
Why doesn't Map extend Collection?+
Collection's methods assume a bag of single values — add, contains(element), an iterator of elements. A Map's unit is an entry and its core operations take keys, which is a different contract. It exposes collection views instead: keySet, values, entrySet.
What does 'program to the interface' actually buy you?+
Exactly one line of your code names the implementation; everything else sees the contract. Swapping ArrayList→LinkedList, HashMap→TreeMap, or wrapping in unmodifiableList becomes a one-line change, and injected/mocked interfaces keep working in tests.
How does for-each relate to the hierarchy?+
It is compiler sugar for an Iterator loop over anything implementing Iterable. That's why it works on every Collection but not on a Map — and why implementing Iterable makes your own type for-each-able.
What is RandomAccess, and why should it change your algorithm choice?+
A marker interface meaning get(i) is O(1) — ArrayList and arrays have it, LinkedList doesn't. Generic algorithms branch on it: binarySearch index-hops on RandomAccess lists and iterator-walks otherwise, so binary search over a LinkedList is O(n) hops, not O(log n).
What does fail-fast mean — does it make a collection thread-safe?+
Structural modification outside the iterator trips a modification-count check and throws ConcurrentModificationException on the next step. It catches bugs in single-threaded code; it is not synchronisation. For real sharing, use the java.util.concurrent collections.
What did Java 21 add on top of this hierarchy?+
The Sequenced interfaces — SequencedCollection, SequencedSet and SequencedMap — give ordered collections one shared vocabulary for the ends: getFirst, getLast, addFirst, addLast and reversed().
List and Deque extend SequencedCollection; LinkedHashSet and SortedSet extend SequencedSet; LinkedHashMap and SortedMap extend SequencedMap. Existing code kept compiling because the new interfaces slotted in above behaviour that already existed — and reversed() is a live view backed by the original collection, not a copy.
Common misconception: That Sequenced replaces SortedSet or Deque — it unifies their end operations; sorted order and double-ended access remain their own promises.
Follow-up: Why does reversed() return a view instead of copying the list?