The BackendVol. 3 · Part III
0 / 0

Shelves / The Backend

BE·35

Collections

Lists, sets, maps, queues and deques, and how they're built: ArrayList versus LinkedList, HashMap's buckets and treeification, LinkedHashMap, TreeMap's red-black tree, PriorityQueue's heap, ConcurrentHashMap. Covers the equals/hashCode contract, ordering with Comparable and Comparator, iteration and fail-fast behaviour, complexity and memory, compared with the collections of Go, Rust, C++, Zig, C#, Python and the functional languages.

36 topics · ~36 min read · 31-question quiz
Updated Suggest a correction

Start here: holding many things at once

Four shapes of data

Almost every backend holds groups of things: the dishes on a menu, the tags on a dish, the stock of each item, the orders waiting for the kitchen. Java's collections framework (java.util) gives you four basic shapes, and choosing the right one is most of the skill:

Shape Interface Use when Class
Ordered, duplicates OK List Order matters; by position ArrayList
No duplicates Set "Is X in here?"; uniqueness HashSet
Key → value lookup Map Find a value by its key HashMap
Waiting line Queue, Deque Arrival order, or either end ArrayDeque

Declare variables by the interface (List<Dish> menu = new ArrayList<>()) so you can swap the implementation without touching the code that uses it. The part in angle brackets is the element type (a generic, chapter 36): a List<Dish> can only hold dishes, and the compiler checks it.

All four in one program

Java
record Dish(String name, int pricePaise, String category) {}

List<Dish> menu = new ArrayList<>(List.of(new Dish("Masala dosa", 9000, "breakfast"), new Dish("Idli", 5000, "breakfast"),
    new Dish("Thali", 18000, "lunch"), new Dish("Samosa", 2000, "snacks"), new Dish("Vada", 4000, "breakfast")));
menu.get(2).name();                                              // by position

Set<String> tags = new HashSet<>(List.of("veg", "spicy", "veg", "south-indian"));

Map<String, Integer> stock = new HashMap<>();
stock.put("Masala dosa", 40); stock.put("Idli", 120);
stock.merge("Idli", -20, Integer::sum);                          // update in place: 120 + (-20)
stock.getOrDefault("Vada", 0);                                   // a missing key returns the default, not null

Deque<String> kitchenQueue = new ArrayDeque<>();
kitchenQueue.offer("order 41"); kitchenQueue.offer("order 42"); kitchenQueue.offer("order 43");
kitchenQueue.poll();                                             // takes "order 41" off the front
Text
List keeps order and duplicates, index access: Thali
Set drops duplicates: 3 tags, contains spicy? true
Map looks up by key: idli stock 100, vada 0
Queue is first in, first out: cooking order 41, next order 42

Four details worth remembering. List.of(...) makes an immutable list; wrapping it in new ArrayList<>(...) gives you a copy you can change. The set silently dropped the second "veg". map.get returns null for a missing key, which is why getOrDefault and merge exist. And ArrayDeque is the right queue (and stack) for single-threaded code; the old Stack and Vector classes are legacy.

Sorting and grouping

Java
menu.sort(Comparator.comparing(Dish::category).thenComparing(Dish::pricePaise, Comparator.reverseOrder()));

Map<String, List<String>> byCategory = menu.stream()
    .collect(Collectors.groupingBy(Dish::category, TreeMap::new, Collectors.mapping(Dish::name, Collectors.toList())));
Text
sorted by category, then price high→low: [Masala dosa, Idli, Vada, Thali, Samosa]
grouped: {breakfast=[Masala dosa, Idli, Vada], lunch=[Thali], snacks=[Samosa]}

A Comparator describes an ordering; comparing and thenComparing build one from the fields you sort by, so you never write comparison arithmetic by hand. groupingBy builds a map from a key to the list of matching items; passing TreeMap::new keeps the keys sorted (a HashMap has no predictable order).

Why the choice matters: speed

The shapes differ hugely in how fast common operations are. "Is this id in the list?" on an ArrayList checks every element in turn; a HashSet jumps straight to the right slot using the element's hash code. The lab measured 1,000 lookups among 200,000 numbers:

Text
1,000 contains() on 200k elements: ArrayList 253.3 ms | HashSet 0.144 ms | TreeSet 0.270 ms

That's about 1,700×. The terms you'll see everywhere describe how the cost grows with size n: O(1) (constant: hash lookups, ArrayList.get(i)), O(log n) (grows slowly: TreeMap, which keeps keys sorted), O(n) (proportional: searching a list). A loop that does an O(n) lookup on every iteration is O(n²), which is the commonest cause of "it was fast in testing and slow in production".

The hash code contract

Hash-based collections (HashSet, HashMap) find things by first computing hashCode() to pick a slot, then using equals() to compare within it. So any type you use as a key or set member must have equals and hashCode that agree (equal objects, equal hash codes), and the fields they use must not change while the object is in the collection. Records satisfy both automatically, which is a strong reason to use records (or String, Long, enums) as map keys. Chapter 34's lab showed what goes wrong otherwise.

Changing a collection while looping over it

Java
for (Dish d : menu) if (d.pricePaise() < 3000) menu.remove(d);   // throws
menu.removeIf(d -> d.pricePaise() < 3000);                       // correct
Text
removing inside a for-each loop: ConcurrentModificationException
removeIf instead: 4 dishes left

The standard collections are fail-fast: their iterators notice the collection changed underneath them and throw instead of producing wrong results. Despite the name, this has nothing to do with threads. Use removeIf, an explicit Iterator with it.remove(), or build a new collection. And the collections in this section are not thread-safe at all: sharing a HashMap between threads loses data (the lab lost 28,064 of 800,000 entries); use ConcurrentHashMap.

How deep to go in collections

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Choose List, Set, Map or Queue for a problem and use their common methods
L2 Sort with comparators, group with collectors, use immutable collections and safe iteration
L3 Explain how ArrayList, HashMap, TreeMap, PriorityQueue and ConcurrentHashMap work inside, with their complexity and memory costs
L4 Diagnose O(n²) lookups, broken keys, ConcurrentModificationException, unsafe sharing and boxing overhead in real code
L5 Choose specialised structures (primitive collections, persistent collections, concurrent queues) from measurements
L6 Set collection conventions (immutability at boundaries, key types) for a codebase

The collection landscape

Interfaces and implementations

Java's Collections Framework (JDK 1.2, 1998) separates interfaces (what operations are available) from implementations (how they're stored):

Iterable Collection SequencedCollection List Set Queue Deque SortedSet Map SequencedMap NavigableMap List:ArrayList · LinkedList · CopyOnWriteArrayList Set:HashSet · LinkedHashSet · TreeSet · EnumSet Queue:ArrayDeque · PriorityQueue · LinkedBlockingQueue Map:HashMap · LinkedHashMap · TreeMap · EnumMap · ConcurrentHashMap
The core Java collection interfaces (top) and their main implementations (bottom). Map is a separate hierarchy from Collection. Sequenced interfaces arrived in JDK 21.
Interface Contract Main implementations
List<E> Ordered by index, duplicates allowed ArrayList (default), LinkedList, CopyOnWriteArrayList
Set<E> No duplicates (by equals) HashSet (default), LinkedHashSet (insertion order), TreeSet (sorted), EnumSet
Map<K,V> Unique keys → values HashMap (default), LinkedHashMap, TreeMap, EnumMap, ConcurrentHashMap
Queue<E> Head removal (FIFO or priority) ArrayDeque, PriorityQueue, LinkedList, the blocking queues
Deque<E> Insert and remove at both ends; also a stack ArrayDeque (use it instead of Stack and LinkedList)
SequencedCollection / SequencedMap (JDK 21) A defined encounter order: getFirst, getLast, addFirst, reversed() List, Deque, LinkedHashSet, LinkedHashMap, TreeSet/TreeMap

Program to the interface (List<Order> orders = new ArrayList<>()). Callers then depend on the contract, and you can change the implementation without touching them.

Equivalents across languages

Concept Java C# Go Rust C++ Zig Python
Dynamic array ArrayList List<T> slice []T Vec<T> std::vector std.ArrayList list
Hash map HashMap Dictionary built-in map[K]V HashMap (hashbrown) std::unordered_map std.HashMap, std.AutoHashMap dict
Insertion-ordered map LinkedHashMap — (OrderedDictionary .NET 9) — indexmap crate — std.ArrayHashMap dict (ordered since 3.7)
Sorted map TreeMap (red-black) SortedDictionary (red-black) — (third-party, B-trees) BTreeMap (B-tree) std::map (red-black) — (std.Treap) — (sortedcontainers)
Hash set HashSet HashSet map[K]struct{} HashSet std::unordered_set std.AutoHashMap(K, void) set
Deque ArrayDeque LinkedList, Queue — (slices, container/list) VecDeque std::deque — collections.deque
Priority queue PriorityQueue (min-heap) PriorityQueue<T,P> container/heap (interface-based) BinaryHeap (max-heap) std::priority_queue (max-heap) std.PriorityQueue heapq (min-heap functions)
Concurrent map ConcurrentHashMap ConcurrentDictionary sync.Map, or map + RWMutex DashMap, or Mutex<HashMap> — (TBB, folly) — dict + lock (or the GIL)
Immutable List.of, Map.of ImmutableList, FrozenDictionary — (ownership makes this mostly unnecessary) const const tuple, frozenset

Two language-design differences stand out:

  • Go has exactly two built-in generic containers, slices and maps, plus generic helper packages since 1.21 (slices, maps). Most Go code uses only those.
  • Zig and C don't allocate behind your back: every growable collection takes an allocator explicitly (C uses malloc or a custom one). In Zig, var list = std.ArrayList(u32).init(allocator) was the older API. Since Zig 0.15 the default ArrayList is "unmanaged": you pass the allocator to each operation that may allocate, as in list.append(allocator, x).

Lists

ArrayList: the dynamic array

ArrayList stores elements in a backing Object[] array with spare capacity. When it fills up, it allocates a bigger array (about 1.5× the old size in the JDK) and copies everything over.

elementData (capacity 10, size 10): full ref ref ref ref ref ref ref ref ref ref add(x): grow to 10 + 10/2 = 15, Arrays.copyOf ref ref ref ref ref ref ref ref ref ref x · · · · each ref (4 bytes with compressed oops) → separate heap object (e.g. Integer, 16 bytes) Amortised: n appends cost O(n) total copies, so O(1) each on average. Pre-size with new ArrayList<>(expected) when you know n; trimToSize() releases slack.
ArrayList growth. Appends fill spare capacity in O(1); when full, a larger array is allocated and elements copied. Doubling-style growth makes append amortised O(1).
Operation ArrayList LinkedList
get(i) / set(i) O(1) O(n), walking from the nearer end
add(e) at end Amortised O(1) O(1)
add(0, e) / remove(0) O(n), shifting with System.arraycopy (a fast memmove) O(1)
remove(i) in the middle O(n) shift O(n) to find the node, O(1) to unlink
Iteration Sequential memory: cache-friendly Pointer chasing: cache misses at every node
Memory per element ~4 bytes (the reference) + slack ~24 bytes per node (header + item + next + prev) + the reference

Use ArrayList (or ArrayDeque for queue and stack behaviour). Practically never use LinkedList. Its theoretical O(1) insertion only helps if you already hold an iterator at the position, and even then cache misses make it slower than shifting an array for most realistic sizes (Vol. 1 ch. 7 covers cache behaviour). Joshua Bloch, who wrote LinkedList, has said he never uses it. The same conclusion holds in C++ (std::vector over std::list), Rust (Vec/VecDeque over LinkedList) and Go (slices over container/list).

Rust's documentation says it directly: "It is almost always better to use Vec or VecDeque because array-based containers are generally faster, more memory efficient, and make better use of CPU cache."

Removing elements and other list pitfalls

Java
List<Integer> ids = new ArrayList<>(List.of(10, 20, 30));
ids.remove(1);                      // removes INDEX 1 (the value 20): remove(int index)
ids.remove(Integer.valueOf(10));    // removes the VALUE 10: remove(Object o)

// Arrays.asList returns a fixed-size list backed by the array: set() works, add()/remove() throw
List<String> fixed = Arrays.asList("a", "b");
// fixed.add("c");                  // UnsupportedOperationException

// subList is a VIEW: structural changes to the parent invalidate it
List<Integer> head = ids.subList(0, 1);

// Removing while iterating: use removeIf or an explicit Iterator, never list.remove inside for-each
ids.removeIf(id -> id > 15);

Hashing

How a hash table works

A hash table maps a key to a bucket index with a hash function, giving average O(1) lookups (Vol. 1 ch. 2 covers hashing theory). Collisions, where two keys land in the same bucket, are resolved by chaining (each bucket holds a list) or open addressing (probe for another slot in the same array).

Interactive diagram: A hash table: buckets, collisions and growing. It needs JavaScript; the text around it says the same.

Java's HashMap:

  • A table of Node<K,V>[] with a power-of-two length (16 by default), so the index is hash & (n − 1): a bit mask instead of a slow modulo.
  • Hash spreading: h ^ (h >>> 16) mixes the high bits into the low bits. Otherwise keys whose hashCodes differ only in high bits would all collide under the mask.
  • Chaining with linked nodes. When a single bucket reaches 8 nodes (and the table has at least 64 buckets), it treeifies into a red-black tree ordered by hash (and by Comparable if keys implement it). Worst-case lookup in that bucket drops from O(n) to O(log n). This defends against hash-flooding attacks and terrible hashCodes. It untreeifies at 6.
  • Load factor 0.75: when size > capacity × 0.75, the table doubles and entries are redistributed. Because the size is a power of two, each node either stays at index i or moves to i + oldCap, depending on one bit of its hash.
  • null: one null key (hash 0) and any number of null values are allowed. ConcurrentHashMap and Map.of reject nulls.
key.hashCode() h ^ (h >>> 16) h & (n - 1) → 3 table (n = 16) 0 1 2 3 … 9 15 h,k,v,next h,k,v,next hash, thenequals() red-black tree bin (> 8 nodes) resize at size > 0.75n: double n; a node stays at i or moves to i + oldN constant hashCode → one bucket → tree bin, O(log n) at best mutating a key after insertion → wrong bucket → entry unreachable
HashMap internals. hashCode is spread, masked to a bucket, then the bucket's chain (or tree, past 8 entries) is searched with equals.

Hash tables in other languages

Language Strategy Notes
Java HashMap Chaining + treeified bins Iteration order is unspecified (it depends on hashes and capacity). Don't rely on it
Python dict Open addressing + a separate compact entries array Insertion-ordered (guaranteed since 3.7). str hashes are randomised per process (PYTHONHASHSEED) against hash flooding
Go map Swiss tables since Go 1.24 (earlier: buckets of 8 with overflow chains) Iteration order is deliberately randomised so nobody depends on it. Not safe for concurrent writes: the runtime detects some races and crashes with fatal error: concurrent map writes
Rust HashMap SwissTable (the hashbrown crate): open addressing with SIMD-probed control bytes The default hasher is SipHash-1-3, randomly keyed: DoS-resistant but slower. Swap in ahash/FxHash for trusted keys
C++ std::unordered_map Chaining with node per element, mandated by the standard's iterator and reference-stability rules Slow-ish (allocation per insert, pointer chasing). Many teams use absl::flat_hash_map or boost::unordered_flat_map
C# Dictionary Chaining through an entries array (indices, not pointers) Randomised string hashing since .NET Core
Zig std.HashMap Open addressing with linear probing and metadata bytes ArrayHashMap keeps insertion order and gives fast iteration

Hash flooding (CVE-2011-4815 and friends, 2011): attackers send HTTP form parameters crafted to collide, turning hash insertion into O(n²) and taking servers down with small requests. The defences are randomised hash seeds (Python, Rust, Go, C#, Ruby) or tree-shaped buckets (Java 8, which kept String.hashCode deterministic because its formula is part of the spec).

The equals and hashCode contract

Hash-based collections rely on two methods every Java object inherits from Object. The contract:

  1. Reflexive, symmetric, transitive, consistent: x.equals(x); x.equals(y) ⇔ y.equals(x); transitivity; repeated calls agree. x.equals(null) is false.
  2. Equal objects must have equal hash codes. (Unequal objects may share a hash code, which is a collision.)
  3. hashCode must not change while the object is in a hash collection, so don't use mutable fields as keys.

Breaking rule 2 is the classic bug: you override equals but not hashCode, so two "equal" objects land in different buckets and set.contains(copy) returns false.

public final class Sku {
    private final String code;
    private final int variant;

    public Sku(String code, int variant) { this.code = code; this.variant = variant; }

    @Override public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Sku other)) return false;      // instanceof pattern; final class, so symmetric
        return variant == other.variant && code.equals(other.code);
    }
    @Override public int hashCode() { return Objects.hash(code, variant); }  // or 31 * code.hashCode() + variant
}
// Or just: public record Sku(String code, int variant) {}: equals/hashCode generated correctly.

// The mutable key bug
var key = new ArrayList<>(List.of(1));
var map = new HashMap<List<Integer>, String>();
map.put(key, "one");
key.add(2);                       // key's hashCode changes
map.get(key);                     // null: looks in the wrong bucket
map.containsValue("one");         // true: the entry is still there, just unreachable by key

equals with inheritance is a trap: if ColoredPoint extends Point adds a field to equals, symmetry or transitivity breaks (Effective Java item 10). There's no way to extend an instantiable class with a new value component while keeping the equals contract. Use composition, or make value classes final (records are final).

IdentityHashMap deliberately uses == and System.identityHashCode, which is useful for graph traversal (visited sets of objects regardless of equals). WeakHashMap holds keys weakly, so entries disappear when the key is otherwise unreachable.

Ordered and specialised collections

LinkedHashMap and LinkedHashSet

LinkedHashMap is a HashMap whose entries are also threaded on a doubly linked list, so iteration follows insertion order (or access order if constructed with accessOrder = true). With removeEldestEntry, it becomes an LRU cache in a few lines:

Java
final class Lru<K, V> extends LinkedHashMap<K, V> {        // a rare legitimate use of extension: documented hook
    private final int max;
    Lru(int max) { super(16, 0.75f, true); this.max = max; } // accessOrder = true: get() moves to the end
    @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > max; }
}
// Not thread-safe: wrap it or use Caffeine for real caches (chapter 53).

In JDK 21+, LinkedHashMap is a SequencedMap: firstEntry(), pollLastEntry(), putFirst() and reversed().

TreeMap and TreeSet

TreeMap is a red-black tree (a self-balancing binary search tree, Vol. 1 ch. 2): get, put and remove are O(log n), and keys are kept sorted by Comparable or a supplied Comparator. Its value is the navigation API:

Java
NavigableMap<Instant, Price> prices = new TreeMap<>();
prices.floorEntry(t);              // greatest key ≤ t: "price in effect at time t"
prices.ceilingKey(t);              // smallest key ≥ t
prices.headMap(t, false);          // view of keys < t
prices.subMap(from, true, to, false);   // range view [from, to)
prices.descendingMap();            // reverse-ordered view
prices.pollFirstEntry();           // remove and return the smallest

TreeMap uses only the comparator for equality. If compare(a, b) == 0, the keys are considered equal even if a.equals(b) is false. That's why Comparator should be consistent with equals, and why new TreeSet<>(String.CASE_INSENSITIVE_ORDER) treats "A" and "a" as one element. BigDecimal is the famous inconsistency: new BigDecimal("2.0") and "2.00" are equal by compareTo but not by equals, so a HashSet holds both while a TreeSet holds one.

Other languages: Rust's BTreeMap is a B-tree with nodes holding several keys each. That's more cache-friendly than a binary tree, and it's the standard library's ordered map (range(..) gives navigation). C++ std::map is typically red-black, with lower_bound/upper_bound. Go has no ordered map in the standard library: use a sorted slice with slices.BinarySearch, or a third-party B-tree.

Queues, deques and PriorityQueue

  • ArrayDeque: a circular buffer with head and tail indices that wrap around a power-of-two array. O(1) at both ends, no nodes. It's the default for stacks (push/pop) and FIFO queues (offer/poll). It doesn't allow nulls (null is its "empty" sentinel). The legacy Stack class extends Vector, so it's synchronised and exposes index access. Avoid it.
  • PriorityQueue: a binary min-heap in an array (children of index i are at 2i+1 and 2i+2; Vol. 1 ch. 2). offer/poll are O(log n), peek is O(1), remove(Object) is O(n). Iteration order is not sorted; only repeated poll() yields sorted order. Pass Comparator.reverseOrder() for a max-heap. Rust's BinaryHeap and C++'s priority_queue are max-heaps by default (Rust uses Reverse(x) for min). Go's container/heap asks you to implement heap.Interface on your own slice type.
  • Blocking queues (java.util.concurrent): ArrayBlockingQueue (bounded, one lock), LinkedBlockingQueue (optionally bounded, separate put/take locks), SynchronousQueue (no capacity: hand-off), PriorityBlockingQueue, DelayQueue, and LinkedTransferQueue. They're the backbone of producer/consumer designs and thread pools (chapter 38). Go's buffered channels play the same role as a language primitive.
Java
// Top-k with a bounded min-heap: O(n log k)
static List<Order> topK(Iterable<Order> orders, int k) {
    var heap = new PriorityQueue<Order>(Comparator.comparing(Order::total));   // min-heap by total
    for (var o : orders) {
        heap.offer(o);
        if (heap.size() > k) heap.poll();            // evict the smallest
    }
    var out = new ArrayList<>(heap);
    out.sort(Comparator.comparing(Order::total).reversed());
    return out;
}

EnumSet and EnumMap

When keys are enum constants, EnumSet is a bit vector (one long for ≤ 64 constants) and EnumMap is an array indexed by ordinal. Both are faster and smaller than hash-based collections and iterate in declaration order. Use EnumSet.of(READ, WRITE) instead of bit flags (int perms = READ | WRITE). Rust uses the bitflags/enumset crates, C uses manual bit flags, and Zig uses std.EnumSet and std.EnumArray.

Ordering

Comparable and Comparator

Two ways to define order in Java:

  • Comparable<T>: the type's natural ordering, implemented by the type itself (String, Integer, LocalDate, BigDecimal). One per type.
  • Comparator<T>: an external ordering that you can build and combine. You can have as many as you need.

compare(a, b) returns a negative number, zero or a positive number. It must be antisymmetric, transitive and consistent, and ideally consistent with equals.

// Comparator combinators: readable, null-safe, and composable
Comparator<Order> byPriorityThenNewest =
    Comparator.comparing(Order::priority)                         // enum natural order
              .thenComparing(Order::createdAt, Comparator.reverseOrder())
              .thenComparing(Order::id);                          // tie-breaker: deterministic ordering

Comparator<Customer> byNameNullsLast =
    Comparator.comparing(Customer::name, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER));

orders.sort(byPriorityThenNewest);

// BUG: subtraction comparators overflow
Comparator<Item> bad = (a, b) -> a.weight - b.weight;    // wrong when values differ by more than Integer.MAX_VALUE
Comparator<Item> good = Comparator.comparingInt(Item::weight);   // or Integer.compare(a.weight, b.weight)

Stability: Java's List.sort/Arrays.sort for objects use TimSort (stable; O(n) on already-sorted runs). Arrays.sort for primitives uses a dual-pivot quicksort (not stable, which doesn't matter for primitives). Python uses TimSort (or its successor Powersort, since 3.11). Rust has sort (stable, driftsort) and sort_unstable (ipnsort, faster). C++ has std::sort (introsort, unstable) and std::stable_sort. Go's slices.Sort is unstable (pdqsort), with slices.SortStableFunc for stable sorting.

Iteration

Iterators and fail-fast behaviour

Java collections expose Iterator<E> (hasNext, next, optional remove), which the enhanced for loop uses. Most non-concurrent collections are fail-fast: they keep a modCount counter of structural modifications, and the iterator checks that it hasn't changed since the iterator was created. If it has, the iterator throws ConcurrentModificationException, even in a single thread:

Java
List<String> names = new ArrayList<>(List.of("a", "b", "c"));
for (String n : names) {
    if (n.equals("a")) names.remove(n);     // ConcurrentModificationException on the next iteration
}
// Fixes:
names.removeIf(n -> n.equals("a"));                    // best
for (var it = names.iterator(); it.hasNext(); ) {      // iterator's own remove is allowed
    if (it.next().equals("a")) it.remove();
}

Fail-fast is best-effort. It isn't a concurrency guarantee: with multiple threads and no synchronisation, you might get a CME, silently corrupted state, or nothing at all.

Concurrent collections are weakly consistent instead. ConcurrentHashMap iterators never throw a CME and reflect some state at or after the iterator's creation. CopyOnWriteArrayList iterators are snapshots.

How other languages handle "modify while iterating":

Language Behaviour
Rust Compile error. Iterating borrows the collection immutably, and push/remove need a mutable borrow. The borrow checker rejects the combination outright. Use retain, drain, or collect the indices first
C++ Iterator invalidation: vector::push_back may reallocate and invalidate all iterators, and erase invalidates those after the erased element. Using an invalidated iterator is UB (crash or silent corruption). The idiom is it = v.erase(it) or std::erase_if (C++20)
Go Deleting map entries during range is allowed and defined (deleted entries won't be produced). Entries added during iteration may or may not appear. Appending to a slice while ranging over it uses the original length
Python RuntimeError: dictionary changed size during iteration for dicts and sets. Lists don't raise, but they skip elements. Iterate over a copy (list(d))
C# InvalidOperationException: Collection was modified (a version counter, like modCount)
Zig No checking in the standard library: modifying invalidates pointers, and safe build modes catch some misuse through assertions
Rust
let mut v = vec![1, 2, 3, 4];
// for x in &v { if *x % 2 == 0 { v.push(*x); } }    // error[E0502]: cannot borrow `v` as mutable
v.retain(|x| x % 2 == 1);                             // [1, 3]

Iteration styles

Internal iteration (forEach, streams in chapter 37) versus external iteration (Iterator, for-loops). Lazy iterator adapters are the norm in Rust (iter().filter().map() compiles to a tight loop), C# (LINQ), Python (generators, itertools), Java streams, C++20 ranges and Go 1.23 range-over-func iterators (iter.Seq[T]).

Complexity and memory

Complexity summary

Structure Access by index Search Insert Delete Ordered iteration
ArrayList / Vec / slice O(1) O(n) O(1)* end, O(n) middle O(n) Insertion order
LinkedList O(n) O(n) O(1) with a node O(1) with a node Insertion order
HashMap / HashSet — O(1) avg, O(log n) treeified worst case O(1)* avg O(1) avg Unspecified
LinkedHashMap — O(1) O(1)* O(1) Insertion or access order
TreeMap / BTreeMap — O(log n) O(log n) O(log n) Sorted
PriorityQueue — O(n) O(log n) O(log n) poll, O(n) arbitrary Not sorted (only poll order)
ArrayDeque / VecDeque O(1) (Rust; Java has no index API) O(n) O(1)* both ends O(1) both ends FIFO

* amortised.

Memory behaviour

Big-O hides constant factors and memory layout, which often dominate on modern CPUs (Vol. 1 ch. 7):

  • Boxing: List<Integer> with 1M elements stores 1M references to 1M Integer objects. That's roughly 4 MB of references plus about 16 MB of objects, compared with 4 MB for an int[], and iteration chases pointers all over the heap. Use primitive arrays, IntStream, or primitive collections (Eclipse Collections, fastutil, HPPC) for big numeric data. Rust Vec<i32>, Go []int32, C# List<int> and C++ vector<int> are all unboxed.
  • HashMap entry overhead: each Node is about 32 bytes (header, hash, key, value, next) plus the table slot, the key object and the value object. A HashMap<Long, Long> with 1M entries can use 80–100 MB. The open-addressing maps in Rust, Abseil, Python and Go store entries inline and use far less.
  • Capacity slack: ArrayList keeps up to ~50% unused capacity, and HashMap keeps the table ≥ 25% empty by design. Pre-size when you know the size: HashMap.newHashMap(expected) (JDK 19) computes the capacity for the load factor for you, whereas new HashMap<>(n) treats n as the capacity, which resizes before n entries.
  • Measuring: JOL (Java Object Layout) shows exact object sizes. Heap histograms (jcmd <pid> GC.class_histogram) show which collections dominate (chapter 41).

Immutable and unmodifiable collections

Java
List<String> a = List.of("x", "y");                     // immutable, compact, rejects nulls (JDK 9)
List<String> b = List.copyOf(mutable);                   // immutable copy (no copy if already immutable)
List<String> c = Collections.unmodifiableList(mutable);  // read-only VIEW: changes to 'mutable' show through
List<String> d = stream.toList();                        // JDK 16: unmodifiable (allows nulls)
var e = Collectors.toUnmodifiableList();                 // collector variant

Map.of iteration order is randomised per JVM run (deliberately, like Go maps), so code that accidentally depended on order fails fast in tests.

Concurrent collections

ConcurrentHashMap

ConcurrentHashMap (CHM) is the default thread-safe map. In JDK 8+:

  • Reads are lock-free: get reads volatile table entries without locking.
  • Writes lock per bin: inserting into an empty bin uses a CAS (compare-and-swap, chapter 38). Inserting into an occupied bin synchronized-locks only that bin's first node. Different bins proceed in parallel.
  • Resizing is cooperative: threads that encounter a resize in progress help transfer bins.
  • Size is tracked with striped counters (LongAdder-style) to avoid contention.
  • No nulls: get(k) == null must unambiguously mean "absent", since there's no way to atomically check containsKey and then get.

The important lesson: thread-safe operations don't make compound operations atomic:

Java
var counts = new ConcurrentHashMap<String, Integer>();

// RACE: check-then-act across two calls; two threads can both read 5 and both write 6
Integer old = counts.get(word);
counts.put(word, old == null ? 1 : old + 1);

// Atomic per key:
counts.merge(word, 1, Integer::sum);
counts.compute(word, (k, v) -> v == null ? 1 : v + 1);
counts.computeIfAbsent(userId, id -> new CopyOnWriteArrayList<>()).add(event);
// Keep compute functions short and side-effect-free: they run while holding the bin lock,
// and must not modify the map itself (that can deadlock or throw IllegalStateException).

// High-contention counters: LongAdder values
var hits = new ConcurrentHashMap<String, LongAdder>();
hits.computeIfAbsent(path, p -> new LongAdder()).increment();

Collections.synchronizedMap(m) wraps every method in one lock: correct, but serialised, and you must still synchronise manually while iterating. Hashtable and Vector are legacy fully synchronised classes, so don't use them in new code.

Other concurrent collections: CopyOnWriteArrayList (each write copies the array, which suits rarely modified listener lists with frequent iteration), ConcurrentSkipListMap (a sorted, lock-free concurrent NavigableMap), ConcurrentLinkedQueue (a lock-free Michael-Scott queue) and the blocking queues above.

Concurrent maps in other languages

// Go: plain maps are not safe for concurrent use. Options:
type Counter struct {
    mu sync.RWMutex
    m  map[string]int
}
func (c *Counter) Inc(k string) { c.mu.Lock(); c.m[k]++; c.mu.Unlock() }

// sync.Map: optimised for (1) write-once/read-many keys, or (2) goroutines touching disjoint keys.
var cache sync.Map
v, loaded := cache.LoadOrStore("k", compute())     // note: compute() runs even if the key exists

Functional languages: persistent collections

In Haskell, Clojure, Scala (immutable), Elixir and F#, collections are immutable and persistent: "adding" returns a new collection that shares structure with the old one:

  • Cons lists (x : xs in Haskell, [h | t] in Elixir): O(1) prepend sharing the tail; O(n) indexing.
  • Hash array mapped tries (HAMTs): Clojure's PersistentHashMap, Scala's HashMap, Elixir maps above 32 keys. These are 32-way branching tries over hash bits, so updates copy only the path from root to leaf (about log₃₂ n ≈ 4 nodes for a million entries).
  • Balanced trees: Haskell's Data.Map (size-balanced trees), OCaml's Map.
  • RRB-vectors: efficient immutable indexed sequences.
(def v1 {:a 1 :b 2})
(def v2 (assoc v1 :c 3))     ; v1 is unchanged; v2 shares most nodes with v1
;; Safe to share across threads with no locks; old versions remain valid (time travel, undo).

The trade-off is that persistent collections are slower per operation than mutable arrays and hash tables (more indirection, more allocation). They buy fearless sharing, cheap snapshots and simpler reasoning, which is exactly what concurrent and event-sourced systems want.

Lab: choosing the wrong collection, measured

Run on JDK 21 with java -Xmx2g Lab.java; timings are from the third round, after the JIT has compiled the loops. Absolute numbers vary by machine; the ratios are the lesson.

Experiment 1: ArrayList versus LinkedList

Both lists hold 200,000 integers. Each operation is done 2,000 times:

Java
for (int i = 0; i < 2000; i++) s += list.get(i * 97 % n);      // random access
for (int i = 0; i < 2000; i++) list.add(n / 2, i);              // insert in the middle
for (int v : list) s += v;                                      // full iteration
Text
2,000 random get(i):          ArrayList 0.20 ms | LinkedList 307.7 ms
2,000 inserts in the middle:  ArrayList 15.3 ms | LinkedList 592.9 ms
full iteration:               ArrayList 0.73 ms | LinkedList 1.52 ms

LinkedList lost every test, including inserting in the middle, the one operation textbooks say it's good at. Insertion into a linked list is O(1) only once you're standing at the right node; getting there means walking about 100,000 nodes, each a separate heap object with poor cache locality. ArrayList has to shift 100,000 references per insert, but that's one System.arraycopy over contiguous memory, which modern CPUs do extremely fast (Volume 1 chapter 7). Use ArrayList for lists and ArrayDeque for queues; LinkedList almost never wins in practice (its own author, Joshua Bloch, has said he never uses it).

Experiment 2: contains on a list versus a set

Text
1,000 contains() on 200k elements: ArrayList 253.3 ms | HashSet 0.144 ms | TreeSet 0.270 ms

A list scan is O(n); the hash set computes the element's hash and checks one bucket, O(1); the tree set walks about 18 levels of a red-black tree, O(log n). Here that's about 1,700× between list and hash set. This is the commonest accidental O(n²) in backend code: ids.contains(x) inside a loop over another large collection, or list.stream().filter(...).findFirst() per request to find an item by id. Build a Set or a Map<Id, Item> once and look up in it.

Experiment 3: a HashMap shared between threads

Eight threads each put 100,000 distinct keys into one map, so no two threads ever write the same key:

Java
for (int th = 0; th < 8; th++) { int base = th * 100_000;
    pool.submit(() -> { for (int i = 0; i < 100_000; i++) m.put(base + i, i); }); }
Text
8 threads × 100,000 puts into HashMap           → size 771,936 (expected 800,000)
8 threads × 100,000 puts into ConcurrentHashMap → size 800,000 (expected 800,000)

The plain HashMap silently lost 28,064 entries, without any exception. Two threads inserting into the same bucket, or one thread resizing the table while another writes, overwrite each other's links. (Before JDK 8, concurrent resizes could even create a cycle in a bucket's list and send a get into an infinite loop at 100% CPU.) The result changes from run to run, which makes these bugs hard to reproduce. ConcurrentHashMap locks per bin and resizes cooperatively, and was exact. Wrapping in Collections.synchronizedMap is also correct but serialises every access; chapter 38 covers the alternatives.

Experiment 4: a view is not a copy

Java
List<String> src = new ArrayList<>(List.of("dosa"));
List<String> view = Collections.unmodifiableList(src), copy = List.copyOf(src);
src.add("idli");
Text
after changing the source: unmodifiableList view = [dosa, idli] | List.copyOf = [dosa]

Collections.unmodifiableList returns a read-only view: callers can't modify it, but they see every change made through the original. List.copyOf (and List.of, Set.copyOf, Map.copyOf) makes an independent immutable copy. When a class hands out its internal state (chapter 34's encapsulation), a view still lets readers observe later changes and race with writers on another thread; a copy is a snapshot. List.copyOf of an already-immutable list returns the same list without copying, so defensive copies are cheap when everyone uses immutable collections.

Try it yourself

  1. Repeat experiment 1 inserting at the front (add(0, x)) and with ArrayDeque.addFirst. Which is fastest now?
  2. In experiment 2, use a record Id(long v) with a deliberately bad hashCode() that returns 1. How slow does HashSet get, and why is it still not as slow as the list? (Hint: treeification.)
  3. Run experiment 3 ten times and record the sizes. Then replace HashMap with Collections.synchronizedMap(new HashMap<>()) and compare its speed with ConcurrentHashMap.
  4. Measure memory per entry for HashMap<Integer,Integer> versus int[] pairs with jcmd <pid> GC.class_histogram, and compare with Go's map[int]int and Rust's HashMap<i32,i32>.

Revision sheet: collections

Key ideas

  • Four shapes: List (ordered, indexed), Set (unique), Map (key → value), Queue/Deque (FIFO, both ends). Declare by interface.
  • ArrayList: a growable array (grows by 1.5×), O(1) get, amortised O(1) append, O(n) middle insert done by fast array copies. LinkedList rarely wins.
  • HashMap: an array of bins indexed by spread hash bits; load factor 0.75 triggers a doubling resize; bins with 8+ entries become red-black trees (when the table has 64+ bins).
  • LinkedHashMap keeps insertion (or access) order and makes an LRU cache with removeEldestEntry; TreeMap is a red-black tree with sorted keys and range queries (headMap, ceilingKey); PriorityQueue is a binary heap; EnumMap/EnumSet are arrays/bit sets.
  • equals/hashCode contract: equal objects, equal hashes; key fields immutable. Comparable is natural order; Comparator is any order, composed with comparing/thenComparing; must be consistent with equals for sorted sets.
  • Iteration: fail-fast iterators throw ConcurrentModificationException on structural change; use removeIf or Iterator.remove.
  • Immutability: List.of/copyOf are immutable copies (no nulls); Collections.unmodifiable* are read-only views; JDK 21 added SequencedCollection (getFirst, reversed).
  • Concurrent: ConcurrentHashMap (per-bin locking, compute/merge atomic per key), CopyOnWriteArrayList for read-mostly lists, BlockingQueues for producer/consumer, ConcurrentSkipListMap for sorted.
  • Other languages: Go slices and maps (randomised iteration order), Rust Vec/HashMap (SipHash by default)/BTreeMap, C++ vector/unordered_map/map, C# List<T>/Dictionary, Python list/dict (insertion ordered), persistent collections in Clojure, Scala and Haskell.

Numbers to remember

  • HashMap default capacity 16, load factor 0.75, treeify threshold 8.
  • Lab: LinkedList.get about 1,500× slower than ArrayList, and slower even at middle inserts; list contains about 1,700× slower than HashSet on 200k elements; a shared HashMap lost 28,064 of 800,000 entries.

Pitfalls

  • contains/linear search inside loops (accidental O(n²)).
  • Mutable or inconsistent keys; hashCode missing or using mutable fields.
  • Modifying a collection while iterating it.
  • Sharing non-thread-safe collections across threads; check-then-act on ConcurrentHashMap (if (!containsKey) put) instead of computeIfAbsent.
  • Returning internal collections, or unmodifiable views when a snapshot was needed.
  • Relying on HashMap iteration order; boxing overhead for large numeric collections.

Glossary

  • Bucket/bin: one slot of a hash table's array.
  • Load factor: entries per bin that triggers a resize.
  • Fail-fast iterator: one that throws on concurrent structural modification.
  • Amortised O(1): constant on average over many operations, despite occasional expensive ones (resizes).
  • Persistent collection: an immutable collection whose "modifications" return new versions sharing structure.
  • View: a collection backed by another, reflecting its changes.