HashMap Internals & Collection Choice
KOTLIN › JVM Concurrency
HashMap internals, why sharing one breaks, and choosing the right collection on Android.
The classic live-coding trap is a thread-safe cache: interviewers check you know how HashMap works inside, what exactly goes wrong when threads share one, and which collection to reach for instead. The follow-ups are about the why, so be ready on visibility, happens-before, and check-then-act races. The Android-specific half matters too: SparseArray and ArrayMap trade asymptotic lookup for allocation savings, and a credible answer names both halves of that trade rather than treating them as a free win.
What this covers
- HashMap internals: hashCode picks the bucket, equals resolves collisions within it, load factor (0.75) triggers resize, and long chains treeify (Java 8+)
- The hashCode/equals contract: equal objects must share a hashCode, and mutating a key after insertion strands the entry in the wrong bucket
- Why a shared HashMap breaks: lost updates, stale reads (visibility), and corruption when two threads trigger a resize together
- volatile guarantees visibility and ordering, never atomicity: check-then-act and read-modify-write still race
- happens-before edges: unlock then lock of the same monitor, volatile write then read, Thread.start() and Thread.join()
- Choosing the map: HashMap by default, LinkedHashMap for order and easy LRU caches, TreeMap for sorted keys, ConcurrentHashMap once shared
- ArrayList beats LinkedList in practice because contiguous memory beats pointer chasing; use ArrayDeque for queues
- CopyOnWriteArrayList: expensive writes, lock-free reads, snapshot iterators, which is why it suits listener lists
- Collections.synchronizedMap serialises every call and still leaves iteration and compound operations unsafe
- SparseArray and ArrayMap avoid boxing and per-entry nodes for small maps, at O(log n) lookup: measure before converting
- Iteration order is unspecified for HashMap; Kotlin mapOf and setOf are LinkedHashMap-backed and preserve insertion order
Study this topic
- HashMap Internals & Collection Choice explained: the guided lesson
- 16 practice quiz questions
- HashMap Internals & Collection Choice interview questions and answers