Workbench / Volume 3 Exercises: The Backend
V3·35
Collections
Exercises for Volume 3, chapter 35: the four shapes of data (list, set, map, queue); the collection interfaces and implementations and their equivalents in other languages; ArrayList and list pitfalls; how hash tables work and the equals/hashCode contract; LinkedHashMap, TreeMap, queues, deques, PriorityQueue, EnumSet and EnumMap; Comparable and Comparator; iterators and fail-fast behaviour; complexity and memory; immutable and unmodifiable collections; ConcurrentHashMap; and persistent collections. 9 theory questions, 9 programming exercises, 3 cumulative projects, the concepts the chapter leaves out, and 5 senior-level exercises.
Start here: how this chapter's exercises work
The four sets and the locking work as before. The code is Java 21, with Go, Rust and Python for comparison. Every quoted output is real and was measured for these exercises.
Five of the outputs catch experienced developers:
- P2.
Set.of(...)iterated in a different order on two runs of the same program:[vada, dosa, poha, upma, idli]and then[poha, upma, idli, vada, dosa].List.of(...).contains(null)threw aNullPointerException. - P4. A
TreeSetordered only by price kept 2 of 3 dishes, because Idli and Vada cost the same. - P4. Sorting with
(x, y) -> x - yleft[2147483647, -10, 5, -2147483647]unsorted. - P6. Eight threads incrementing a counter in a
ConcurrentHashMapwithgetthenputreached 538,083 of 800,000.mergereached 800,000. - P7. 20,000 keys that all share one hash code took 2,451 ms when they weren't
Comparableand 126 ms when they were. Normal keys took 3.7 ms.
The chapter's lab already measured these, and the exercises build on them rather than repeat them:
ArrayListagainstLinkedList: 0.20 ms against 307.7 ms for randomget, and 15.3 ms against 592.9 ms for inserts in the middle.containson a list, a hash set and a tree set: 253.3 ms, 0.144 ms and 0.270 ms.- A plain
HashMapshared between threads lost 28,064 entries. unmodifiableListis a view andList.copyOfis a snapshot.
Coverage map.
| Chapter component | Exercises |
|---|---|
| four shapes; interfaces and implementations | T1, P1 |
| equivalents across languages | T1, P9 |
| ArrayList; list pitfalls (asList, subList, remove) | T2, P3 |
| how hash tables work; collisions; treeification | T3, P7 |
| equals and hashCode contract | T3, P7 |
| LinkedHashMap/Set; LRU | T4, P5 |
| TreeMap/TreeSet; navigation; comparator consistency | T4, P4 |
| queues, deques, PriorityQueue | T4, P5 |
| EnumSet and EnumMap | T4 |
| Comparable and Comparator | T5, P4 |
| iterators, fail-fast, iteration styles | T5, P3 |
| complexity and memory | T6, P8 |
| immutable and unmodifiable collections | T7, P2 |
| ConcurrentHashMap and atomic operations | T8, P6 |
| persistent collections | T9 |
Theory
T1. Choosing the shape and the implementation
- For each TiffinBox need below, name the shape (list, set, map, queue/deque) and the default implementation, and justify the choice: - the lines of an order; - dish ids a customer has favourited; - menu lookup by dish id; - orders waiting for a kitchen, in arrival order; - delivery jobs by deadline; - the menu sorted by price with "cheapest dish above ₹100"; - order counts per status; - the 1,000 most recently viewed dishes.
- Explain why you declare variables as interfaces (
List<Line> lines = new ArrayList<>()) and why return types matter more than local variables. - Map Java's collections to Go (slices, maps,
container/heap), Rust (Vec,HashMap,BTreeMap,VecDeque,BinaryHeap), Python (list,dict,set,deque,heapq) and JavaScript (Array,Map,Set). Which have ordered maps by default?
T2. ArrayList and list pitfalls
- Explain
ArrayList's internals: a backing array,sizeversus capacity, growth by 1.5× (by that rule about 29 resizes, computed rather than measured, on the way to 1 million elements, with amortised O(1) appends),ensureCapacity,trimToSize, and whyadd(0, x)is O(n) but still beatLinkedListin the lab (15.3 ms against 592.9 ms). - P3 found three traps:
-
Arrays.asListwrites through to the array (settingview[0]changedarr[0]tovada) and throws onadd; - asubListview threwConcurrentModificationExceptionafter the parent list changed; - Go'sappendon slices sharing a backing array:t := append(s, 9); u := append(s, 7)gavet = [0 0 0 7]andu = [0 0 0 7].
Explain each.
3. Explain removing while iterating (ch33's T5), remove(int) against remove(Object) (ch34's P2), and List.of against new ArrayList<>(List.of(...)).
T3. How hash tables work, and the hashCode contract
- Explain Java's
HashMap: - a table of buckets (a power of 2); - thehash()spreading step (h ^ (h >>> 16)); - indexing withhash & (n - 1); - load factor 0.75 and resizing (doubling and splitting each bucket in two); - bucket lists turning into red-black trees after 8 entries (treeification) when the table has at least 64 buckets. - P7 measured collisions. 20,000 keys that all return
hashCode() == 42took 2,451 ms to put and get when the keys weren'tComparable, 126.1 ms when they were (the tree bins could order them), and 3.7 ms for normalIntegerkeys. Also,"Aa".hashCode()and"BB".hashCode()are both 2112. Explain these results, the hash-flooding attacks they enable, and how Java, Python, Go and Rust defend against them. - Restate the
equals/hashCodecontract and its failure modes. Cover the lab's mutable key, ch34's lab and P3–P4, and P6's question ofConcurrentHashMapversusHashMapfor null values.
T4. Ordered and specialised collections
- Explain
LinkedHashMap(insertion or access order, a doubly linked list through the entries,removeEldestEntry). P5's LRU with capacity 3, aftera, b, c,get(a),put(d), held[c, a, d]. Then coverTreeMap/TreeSet(red-black tree, O(log n),floor/ceiling/headMap/tailMap/subMap,descendingMap), and when you need each. - Explain the queue family:
-
ArrayDeque(circular array; stack and queue; no nulls); -PriorityQueue(binary heap). P5 printed itstoStringas[10, 20, 40, 50, 30], while polling gave[10, 20, 30, 40, 50]; - the blocking queues (ch38).
Why is a heap's iteration order not sorted?
3. Explain why EnumSet and EnumMap are faster and smaller than HashSet and HashMap for enum keys, and give TiffinBox uses (allowed statuses, counts by status, dietary flags).
T5. Ordering, iteration and fail-fast behaviour
- Explain
Comparable(natural order) againstComparator(external orders), and modern comparator construction (Comparator.comparing(Dish::paise).thenComparing(Dish::name),reversed(),nullsLast). P4 showed two bugs: - the subtraction comparator(x, y) -> x - yoverflowed and left[2147483647, -10, 5, -2147483647]unsorted; - aTreeSetwith a price-only comparator kept 2 of 3 dishes.
Explain both.
2. What does "consistent with equals" mean for comparators? When does inconsistency matter (TreeSet, TreeMap, ch33's BigDecimal 2.0 against 2.00)?
3. Explain fail-fast iterators (modCount; ch33's T5; P3's subList), weakly consistent iterators (ConcurrentHashMap), and snapshot iterators (CopyOnWriteArrayList). Then compare iteration styles: for-each, Iterator, forEach, streams, and index loops.
T6. Complexity and memory
- Fill in the complexity table:
-
ArrayListget/add/insert-middle/contains; -LinkedListget/insert-at-iterator; -HashMapget/put (average and worst); -TreeMapget/put/floor; -ArrayDequepush/pop; -PriorityQueueoffer/poll/peek/contains; -EnumSetcontains. - P8 estimated memory. A
HashMap<Integer, Integer>with 1 million entries took about 74 bytes per entry, while twoint[]arrays took about 8. Break down where the bytes go: the entry node (header, hash, key, value, next), the boxedIntegerobjects, the table slot, and the load-factor headroom. Then name the alternatives (primitive collections such as fastutil, Eclipse Collections and HPPC; sorted arrays with binary search; bitsets). - When does complexity mislead? Cover constant factors (the lab's
LinkedList), cache effects, smalln, and amortised against worst case (resizes, GC).
T7. Immutable and unmodifiable collections
- Compare four kinds of read-only collection:
- unmodifiable views (
Collections.unmodifiableList): the lab's view saw the change[dosa, idli]; - immutable copies (List.copyOf: the lab's[dosa];List.of;Set.of;Map.of;Stream.toList()); - Guava'sImmutableList; - persistent collections (T9). - P2 found these behaviours of the JDK's immutable collections:
- they reject nulls, and even
contains(null)throws aNullPointerException; -Map.ofthrows on duplicate keys (duplicate key: a); -Set.ofandMap.ofhave randomised iteration order per JVM run.
Why did the JDK designers choose each of these, and what breaks in code that relied on HashSet order or on tests that compare toString() output?
3. When should a method return an immutable collection, and what should it accept? Consider defensive copies (ch33's P7) and List.copyOf on an already-immutable list returning the same instance.
T8. Concurrent collections
- The lab's plain
HashMaplost 28,064 of 800,000 entries across 8 threads. P6 showed that evenConcurrentHashMaploses updates when you writegetthenput: 8 threads × 100,000 increments reached 538,083, whilemergereached 800,000. Explain why, and listConcurrentHashMap's atomic operations (merge,compute,computeIfAbsent,putIfAbsent,replace). - P6 showed that
ConcurrentHashMaprejects null values with aNullPointerExceptionwhileHashMapallows them. Explain why. Then covercomputeIfAbsentpitfalls: long-running functions block the bin, and a recursive update throwsIllegalStateException. Also explainLongAdderfor counters, andsize()againstmappingCount(). - Compare
Collections.synchronizedMap,ConcurrentHashMap,ConcurrentSkipListMap(sorted and concurrent),CopyOnWriteArrayList, and the blocking queues. Then the same needs in other languages: Go'ssync.Mapor a map with async.Mutex(concurrent writes to a plain map panic with "fatal error: concurrent map writes"), Rust'sMutex<HashMap>orDashMap, and Python's GIL.
T9. Persistent collections and functional languages
- Explain persistent (immutable, structurally shared) collections: hash array mapped tries (Clojure, Scala, Vavr), relaxed radix balanced vectors, and why "modifying" a 1-million-element map costs O(log₃₂ n) instead of O(n).
- What do they give a backend? Consider safe sharing across threads, cheap snapshots (undo, event sourcing, versioned configuration), and no defensive copies. What do they cost (constant factors, allocation, interop with
java.util)? - Should TiffinBox use Vavr or PCollections? Decide for three uses: request-scoped data, a configuration snapshot shared by all threads and replaced on reload, and an in-memory order book updated 1,000 times a second.
Programming exercises
P1. The four shapes in one TiffinBox program
Write a program that loads 10,000 random orders, then computes and prints: - the orders in arrival order (list); - the distinct customers (set); - revenue by kitchen (map); - the next 5 deliveries by deadline (priority queue); - the cheapest dish above ₹100 (TreeMap navigation); - counts by status (EnumMap); - the 3 most recently viewed dishes (LRU).
Use only java.util, and declare variables as interfaces.
P2. Immutable collection behaviours
Demonstrate:
- Set.of and Map.of iteration order changing between two JVM runs;
- List.of rejecting nulls, including in contains;
- Map.of rejecting duplicate keys;
- the lab's view against copy.
Then write a test that would be flaky because it compares set.toString(), and fix it three ways.
P3. List views and pitfalls
Reproduce:
- Arrays.asList writing through and refusing add;
- subList failing after a parent change;
- removing during for-each;
- remove(int) against remove(Object);
- Go's slice-aliasing bug.
Fix each, and write a code-review checklist entry for each.
P4. Comparators done right
Show:
- the subtraction comparator failing on large values;
- the price-only TreeSet losing a dish;
- a TreeMap<BigDecimal, …> treating 2.0 and 2.00 as one key while HashMap treats them as two.
Then build the menu's display order: by category in a fixed custom order (Breakfast, Meals, Snacks), then price ascending, then name, with nulls last for dishes without a category. Test it with ties.
P5. LRU cache and priority scheduling
Implement:
- an LRU cache of 3 with LinkedHashMap (access order plus removeEldestEntry), and show its eviction order;
- a delivery scheduler with PriorityQueue<Job> by deadline, showing that toString isn't sorted while polling is;
- a kitchen work queue with ArrayDeque used as a FIFO queue, and as a stack for undo.
Add a test that the LRU evicts the least recently used entry, not the oldest inserted.
P6. ConcurrentHashMap: atomicity and nulls
With 8 threads × 100,000 increments, compare:
- get then put on a ConcurrentHashMap;
- merge;
- compute;
- computeIfAbsent(k, x -> new LongAdder()).increment();
- Collections.synchronizedMap with get/put inside synchronized (map).
Also show the null-value rule, and a computeIfAbsent whose function sleeps for 100 ms, blocking another key in the same bin.
P7. Hash collisions and flooding
Measure HashMap put+get for 20,000 keys with a constant hashCode, both non-Comparable and Comparable, against normal keys. Then generate 2¹⁶ colliding strings from the "Aa"/"BB" pair, insert them, and time it. Finally, write the defensive limits for TiffinBox's HTTP layer (parameter count, JSON field count and depth, body size).
P8. Memory per entry
Estimate the memory for 1 million Integer → Integer entries in a HashMap against two int[] arrays. Then do the same with a primitive map (fastutil Int2IntOpenHashMap) and with a sorted long[] of packed key/value pairs searched with binary search. Report bytes per entry and lookup time, and say when each is worth it.
P9. Collections across languages
Show map iteration order in Go (three loops over the same map), Rust (HashMap against BTreeMap across two runs) and Python (dict insertion order; set order across two runs). Then write the same "count orders per kitchen, print sorted by count descending, then by name" in Java, Go, Rust and Python, with deterministic output in all four.
Cumulative projects (chapters so far: Volume 1, Volume 2, and Volume 3's 33–35)
C1. An in-memory menu and order index
Build MenuIndex and OrderIndex for TiffinBox's kitchen dashboard:
- dishes by id (HashMap);
- dishes by category and price (TreeMap navigation);
- orders by status (EnumMap of insertion-ordered sets);
- orders by deadline (PriorityQueue, or a TreeMap for removal);
- recent searches (LRU).
Make updates atomic from the dashboard's point of view by publishing immutable snapshots through an AtomicReference. Benchmark lookups against the naive list-scanning version with 50,000 orders.
Combines: Volume 1's data structures and complexity (ch 07), Volume 2's dashboard state (ch 25), ch34's encapsulation, and this chapter.
C2. Find and fix accidental O(n²) in a codebase
Given a settlement job that:
- for each of 200,000 orders, calls refundedIds.contains(order.id()) on a List;
- builds a report with String +=;
- looks up dishes with menu.stream().filter(d -> d.id().equals(id)).findFirst() per line;
- removes cancelled orders inside a for-each with an index workaround;
profile it, fix each issue, and show the before/after timings. Add an ArchUnit or Error Prone rule, or a review checklist entry, so each pattern doesn't return.
Combines: Volume 1's complexity analysis and profiling, ch33's StringBuilder result, and this chapter's lookup structures.
C3. A cross-language deterministic export
TiffinBox exports daily menus and order summaries as JSON for partners. The Java service, a Go worker and a Python analytics job must produce byte-identical JSON for the same data, for hashing and caching (ETags; Volume 2 ch19). Define the rules: key order, set and list ordering, number formatting (paise as integers), Unicode normalisation (Volume 1 ch06) and escaping. Implement them in all three, and test with shared golden files.
Combines: Volume 1's encodings and Unicode normalisation, Volume 2's HTTP caching and ETags, ch33's strings and money, and this chapter's ordering.
What the chapter leaves out
SequencedCollection (JDK 21)
JDK 21 added SequencedCollection, SequencedSet and SequencedMap, interfaces for collections with a defined encounter order. They provide uniform getFirst(), getLast(), addFirst, addLast, removeFirst, removeLast and reversed(), implemented by List, Deque, LinkedHashSet, LinkedHashMap, TreeSet and TreeMap. Use them instead of list.get(list.size() - 1) or iterator().next(). Return SequencedMap when order is part of the contract (T7). Note that getFirst on an empty list throws NoSuchElementException.
Primitive and specialised collection libraries
The JDK has no primitive collections: every int key is boxed (P8's ~74 bytes per entry). For heavy in-memory work, use fastutil, Eclipse Collections, HPPC or Koloboke. Other specialised libraries:
- Guava's Multimap, Multiset, BiMap, Table and RangeMap, which save hand-rolled Map<K, List<V>> bugs;
- RoaringBitmap for large integer sets (user segments, feature eligibility).
Know they exist, and justify each dependency.
Caching structures
LinkedHashMap's LRU (P5) is a teaching tool. Production caches need concurrency, size limits by weight, expiry, refresh, statistics and better eviction policies. Caffeine's W-TinyLFU beats LRU on real workloads by protecting frequently used entries from one-off scans. Chapter 53 covers caching, and Caffeine is the default choice on the JVM.
Probabilistic structures
Bloom filters (is this id possibly in the set?), HyperLogLog (approximate distinct counts) and Count-Min sketches (approximate frequencies) answer set questions in tiny memory with bounded error. Uses include: "has this customer possibly seen this promo?", distinct daily users, and top dishes from a stream. Guava provides BloomFilter. Redis (ch53) provides HyperLogLog and Bloom modules.
Collections and serialisation, ORM and APIs
How collections cross boundaries matters as much as which one you pick:
- Jackson deserialises interfaces to default implementations (List becomes an ArrayList);
- JPA wraps collections in its own lazy types (PersistentBag), so equals, hashCode and toString on entities can trigger queries (ch49);
- APIs should never return unbounded collections. Paginate (ch45).
Treat collection sizes from outside as hostile (P7's limits).
Senior exercises
S1. Collection guidelines for the team
Write the team's one-page collection rules: - default implementations; - interfaces in signatures; - immutability for return values; - comparator rules; - concurrency rules; - input limits; - memory-heavy cases; - the checks that enforce them.
Tie each rule to an output from this chapter.
S2. Review a pull request with collection bugs
A PR adds a "kitchen leaderboard":
- a static HashMap<String, Integer> counts updated from request threads with counts.put(k, counts.getOrDefault(k, 0) + 1);
- the top 10 computed by putting all kitchens in a TreeSet ordered by count;
- the leaderboard returned as counts.keySet();
- a test asserting "[Asha's, Ravi's]".equals(top.toString());
- kitchens removed with for (String k : counts.keySet()) if (closed(k)) counts.remove(k);.
Write the review.
S3. Design an in-memory index under memory constraints
TiffinBox wants every API instance to hold a lookup from 6-digit PIN code (about 19,000 codes in India) and dish id (2 million dish–kitchen pairs) to delivery eligibility, refreshed hourly. Instances have 1 GB heaps. Design the structures, estimate the memory, the lookup time and the refresh strategy, and compare with putting it in Redis.
S4. Teach collections with five predictions
Plan a 20-minute session where the audience predicts five outputs:
- the lab's LinkedList middle insert (592.9 ms against 15.3 ms);
- P2's Set.of order across runs;
- P4's TreeSet keeping 2 of 3;
- P6's 538,083 of 800,000;
- P7's 2,451 ms against 3.7 ms.
For each, write the question, the reveal, the explanation in two sentences, and the rule.
S5. Plan the migration off a hand-rolled collection library
A legacy codebase uses an internal com.legacy.util.FastList/FastMap (pre-Java 5, raw types, not thread-safe, equals broken for nested maps) in 1,400 places, including public APIs and serialized sessions. Plan the migration to java.util and decide what to do about the serialized data, the public APIs and the performance claims.