HashMap Internals & Collection Choice Interview Questions
KOTLIN › JVM Concurrency
How does a HashMap work internally?
What a strong answer covers: It's an array of buckets. A key's hashCode is spread and masked to pick a bucket; entries in a bucket are a linked list that turns into a balanced tree when a bucket gets more than 8 entries (Java 8+). Lookups compare the hash then equals. When size exceeds capacity times load factor (0.75), the table doubles and entries are redistributed. Average get and put are O(1).
What is the contract between equals and hashCode, and what breaks if you violate it?
What a strong answer covers: Equal objects must have equal hash codes; unequal objects may share one. If you override equals without hashCode, two equal keys land in different buckets, so map.get returns null for a key that's 'in' the map and sets allow duplicates. Data classes generate both consistently, but mutating a key's fields after insertion breaks it the same way.
Why isn't HashMap thread-safe, and what are the options when you need a thread-safe map?
What a strong answer covers: Concurrent puts can lose updates, corrupt buckets during a resize, or (in old Java versions) create infinite loops. Options: Collections.synchronizedMap (one lock for everything, slow under contention, you must lock manually to iterate), ConcurrentHashMap (fine-grained, the usual choice), or confining the map to one thread or coroutine.
How do you choose between ArrayList, LinkedList, HashMap, LinkedHashMap, TreeMap and ArrayMap or SparseArray on Android?
What a strong answer covers: ArrayList for most lists (cache-friendly, O(1) index access); LinkedList is rarely better in practice. HashMap for fast lookup; LinkedHashMap to keep insertion order or build an LRU cache; TreeMap for sorted keys (O(log n)). Android's ArrayMap and SparseArray use less memory for small maps (hundreds of items) and avoid boxing int keys, but are slower for large ones.
What makes a bad hash code a performance problem, and how would you notice it in a production app?
What a strong answer covers: If many keys share a hash code, they pile into one bucket: lookups degrade to O(n) or O(log n) after treeification, and intentional collisions are even a denial-of-service vector. You'd notice slow lookups in CPU profiles or traces dominated by equals calls. Fixes: hash on all significant fields (data classes do), use immutable keys, avoid mutable objects as keys, and benchmark realistic data.