Java Materials
← Core Java · Chapter 6

Collections Framework and internals

Choose a collection by its actual access pattern, not solely by an asymptotic label. Index access, memory locality, insertion order, duplicates, null policy and concurrency can matter as much as lookup cost.

ArrayList, ArrayDeque and locality

Definition:

Array-backed collections store references in indexed slots; linked collections store links between nodes.

Explanation:

ArrayList grows an internal array and shifts references for middle inserts.

Illustration image:

ArrayList, ArrayDeque and locality. ArrayList slots 0–3 · Middle insert shifts · ArrayDeque head/tail · Linked nodesArrayList, ArrayDeque and localitySource or actorArrayList slots 0–3First boundaryMiddle insert shiftsInspected stateArrayDeque head/tailObservable effectLinked nodes
ArrayList slots 0–3 · Middle insert shifts · ArrayDeque head/tail · Linked nodes

Example:

Worked Java example · see surrounding context in notes
var tasks = new java.util.ArrayDeque<String>();
tasks.addLast("normal");
tasks.addFirst("urgent");
System.out.println(tasks.removeFirst());

Expected behavior. The deque returns urgent without shifting the other element.

Internal working:

Its append cost is amortized, with occasional copy at growth. ArrayDeque uses an array and moving endpoints rather than shifting on normal endpoint operations. LinkedList costs a node allocation per element and pointer traversal for position queries. Compare actual footprint and cache locality, not just big-O.

Interview questions:

Why is LinkedList seldom faster for indexed access?

Finding the index requires traversal. Its cheap node relinking helps only after the position is known.

HashMap, collisions and resizing

Definition:

HashMap uses hash-based bins and equality to resolve candidate keys.

Explanation:

OpenJDK HashMap uses a power-of-two table.

Illustration image:

HashMap, collisions and resizing. Spread hash · Old bin i · New bin i · New bin i + old capacityHashMap, collisions and resizingSource or actorSpread hashFirst boundaryOld bin iInspected stateNew bin iObservable effectNew bin i + old capacity
Spread hash · Old bin i · New bin i · New bin i + old capacity

Example:

Worked Java example · see surrounding context in notes
var visits = new java.util.HashMap<String,Integer>();
visits.merge("order-42", 1, Integer::sum);
visits.merge("order-42", 1, Integer::sum);
System.out.println(visits.get("order-42"));

Expected behavior. The result is 2. If an equivalent key is inserted, the node is updated rather than adding a second logical key.

Internal working:

The spread hash mixes higher bits into the low bits used for indexing. At resize, an old bin's entries can split between its old index and old index plus old capacity. Tree bins depend on thresholds and table size; they are not the Map API contract. Avoid assuming iteration order or designing keys around implementation thresholds.

Interview questions:

What happens to a bin when capacity doubles in current OpenJDK HashMap?

Entries can remain at the old index or move to old index plus old capacity based on the next hash bit.

Views, sorted collections and snapshots

Definition:

A backed view reflects source changes, while a structural snapshot captures elements present at creation.

Explanation:

Arrays.asList and subList are backed views with separate structural limitations.

Illustration image:

Views, sorted collections and snapshots. Backing list [A] · Unmodifiable view · Copy [A] · Source changes to [A,B]Views, sorted collections and snapshotsSource or actorBacking list [A]First boundaryUnmodifiable viewInspected stateCopy [A]Observable effectSource changes to [A,B]
Backing list [A] · Unmodifiable view · Copy [A] · Source changes to [A,B]

Example:

Worked Java example · see surrounding context in notes
var source = new java.util.ArrayList<>(java.util.List.of("A"));
var view = java.util.Collections.unmodifiableList(source);
var copy = java.util.List.copyOf(source);
source.add("B");
System.out.println(view + " " + copy);

Expected behavior. Prints [A, B] [A]. A copy is appropriate when readers need a stable structural snapshot.

Internal working:

An unmodifiable wrapper prevents changes through itself, while source mutations remain visible. List.copyOf makes an unmodifiable structural snapshot, with elements still shared. TreeMap supports sorted navigation, a priority heap exposes only the next element, and Java 21 reversed views preserve backing relationships.

Interview questions:

Does Collections.unmodifiableList freeze the backing list?

It blocks mutations through the wrapper. A caller with the backing reference can still change what the view sees.

Reference subtopics

Lists, queues, deques and heaps

ArrayList offers fast indexed access, amortized append and shifts on middle insertion. LinkedList needs traversal for positional access and allocates nodes. ArrayDeque efficiently serves queues and stacks and rejects null. PriorityQueue maintains a heap and exposes the next priority via peek or poll; its iterator is not sorted.

Hash-based collections

HashMap spreads hashes, indexes a bucket and checks key equality. Collisions may produce lists or tree bins under implementation thresholds. A resize redistributes entries when the load threshold is crossed. HashSet uses hash-key membership. LinkedHashSet and LinkedHashMap preserve defined order. Access-ordered LinkedHashMap moves entries when accessed, useful for a small local LRU policy.

Sorted and specialized types

TreeMap and TreeSet use red-black trees and support lower, floor, ceiling and higher operations and range views. Comparator equality determines uniqueness there. EnumSet packs enum members; EnumMap indexes enum keys. WeakHashMap uses weak keys and can change with GC; IdentityHashMap uses reference keys.

Iteration, views and immutability

Use iterator.remove or supported list-iterator methods for safe structural mutation during traversal. Fail-fast is best effort. subList and Arrays.asList are backed views; the latter has fixed size. Unmodifiable wrappers reflect changes in the backing collection. List.of and List.copyOf are unmodifiable and reject null, but elements can still be mutable.

Java 21 sequenced collections

SequencedCollection, SequencedSet and SequencedMap express encounter order and operations at both ends. reversed returns a reverse-ordered view; it can reflect backing mutations. Sorting constraints or read-only implementations may reject end mutations even when exposing end reads.

Run the complete Java labs ↗ · Java reference ↗