Learning Objectives
- Compare `ArrayList` and `LinkedList` by CPU cache locality, indexed reads, and mid-list insertions.
- Trace how `HashMap` computes bucket indices, resolves collisions, and treeifies at threshold 8 (Java 8+).
- Maintain the `equals()` and `hashCode()` contract cleanly so HashMap lookups never lose keys.
Prerequisites
- Java Classes, Objects, Interfaces, and Generics basics
Choosing Collections by Access Pattern
Choosing between ArrayList, HashSet, ArrayDeque, and HashMap determines whether an API endpoint scales linearly or hits quadratic slowdowns under load.
| Collection | Backing Structure | Avg Read / Lookup | Ordering |
|---|---|---|---|
ArrayList | Resizable Object[] array | O(1) by index | Insertion order |
ArrayDeque | Circular resizable array | O(1) head/tail push/pop | FIFO / LIFO (faster than Stack/LinkedList) |
HashMap | Bucket array + linked/tree bins | O(1) avg (O(log n) worst Java 8+) | Unordered (LinkedHashMap preserves order) |
TreeMap | Red-Black balanced BST | O(log n) | Sorted by natural/Comparator order |
How HashMap Works Since Java 8
When calling map.put(key, val), HashMap mixes high/low hash bits via (h = key.hashCode()) ^ (h >>> 16) to reduce lower-bit clustering, indexes into a power-of-two array (`(n - 1) & hash`), and checks key equality with equals(). Since Java 8, once a single bucket exceeds TREEIFY_THRESHOLD = 8 (with table capacity >= 64), the linked nodes convert to a balanced Red-Black tree so pathological hash collisions degrade to O(log n) instead of O(n).
Up next: transform collections declaratively in Java Stream API & Lambdas or drill Collections MCQs in MockAttempt Mock Tests.
Practical Programming Examples
Grouping, Frequency Counting & Map.computeIfAbsent in Java
Group engineering topics by category cleanly using computeIfAbsent and immutable defensive views.
import java.util.*;
public class CollectionsLab {
public static void main(String[] args) {
Map<String, List<String>> curriculum = new LinkedHashMap<>();
curriculum.computeIfAbsent("Backend", k -> new ArrayList<>()).add("Spring Boot 3");
curriculum.computeIfAbsent("Backend", k -> new ArrayList<>()).add("PostgreSQL MVCC");
curriculum.computeIfAbsent("Cloud", k -> new ArrayList<>()).add("AWS VPC & IAM");
curriculum.forEach((track, topics) ->
System.out.println(track + " -> " + List.copyOf(topics))
);
}
}
Backend -> [Spring Boot 3, PostgreSQL MVCC] Cloud -> [AWS VPC & IAM]
- `LinkedHashMap` preserves insertion order deterministically while preserving O(1) bucket lookups.
- `computeIfAbsent` inserts a backing list once per missing key, eliminating noisy `containsKey` null checks.
- `List.copyOf` returns an unmodifiable view safe for logging or read serialization.
Common Mistakes to Avoid
- Overriding `equals()` on a domain key class without overriding `hashCode()`, breaking HashMap/HashSet lookups completely.
- Modifying a key’s hashable field after placing it inside a `HashMap` or `HashSet`.
- Removing items inside a `for-each` loop instead of `Iterator.remove()` or `collection.removeIf(...)`, triggering `ConcurrentModificationException`.
Production Best Practices
- Prefer `ArrayDeque` over legacy `Stack` or `LinkedList` when implementing queues or stacks.
- Use `List.of()`, `Set.of()`, and `Map.of()` (Java 9+) for small fixed read-only lookups.
Technical Interview Relevance
Nearly every Java fresher and experienced backend interview asks about HashMap collision resolution, fail-fast iterators (`modCount`), and `ConcurrentHashMap`.
Practice & Self-Check Questions
Why does `LinkedList` perform poorly compared to `ArrayList` even for sequential scans?
LinkedList nodes scatter across heap memory (`Node` wrappers + pointers), destroying CPU cache spatial locality and adding 24+ bytes of memory overhead per element.