Skip to content

Try “polymorphism”, “TCP handshake” or “git rebase”.

    Java / Collections, From the Inside

    The Whole Story

    The whole module retold as one story — no new facts, a fast revision of Collections, From the Inside.

    Extra: Revision3 min read

    The Collections Framework separates the job from the product: interfaces List, Set, Queue/Deque and Map say what you need, and you program to them while choosing an implementation underneath (Ch 1). A list is either a row of lockers that moves to a 1.5× bigger row when full — ArrayList, instant by index — or a treasure hunt of nodes — LinkedList, which loses in practice to memory and cache costs (Ch 2). Walking any of them uses a fail-fast iterator that refuses to continue if the collection changed behind its back; remove through the iterator or with removeIf (Ch 3).

    The star is HashMap, the post office of pigeonholes: hashCode is spread and ANDed with a power-of-two capacity to pick a bucket; inside the bucket, the stored hash and then equals find the key; colliding entries form a list that turns into a red-black tree at 8; and past 75% full, the room doubles and entries either stay put or move by exactly the old capacity — all giving O(1) on average, and only if equals and hashCode agree (Ch 4). A HashSet is a HashMap that only cares about keys; LinkedHashMap threads a list through the entries for insertion or access order, which is an LRU cache in five lines (Ch 5). When you need order, the TreeMap dictionary keeps keys sorted in a balanced tree, answering floor, ceiling and range questions in O(log n) (Ch 6), and order itself comes from Comparable (built-in) or Comparator (supplied) — always with Integer.compare, never overflow-prone subtraction (Ch 7).

    Lines and plate piles are both ArrayDeque, a circular array that never shifts, using offer/poll/peek for queues and push/pop for stacks (Ch 8). The emergency room is the PriorityQueue: a binary heap in a plain array, parent at (i−1)/2, where sifting up and down costs O(log n), and a size-k min-heap finds the top k of millions in O(n log k) (Ch 9). Around them sit the Collections utilities and the distinction between a read-only view and a truly immutable copy (Ch 10) — and a decision table that turns Part 0's six needs into six obvious choices (Ch 11).

    Next, Modern Java teaches the lambdas and streams that have quietly appeared in this file, and all the modern syntax you'll see in real Java code.