Java Developer interview question
How does Java HashMap work internally?
HashMap hashes a key into a bucket, resolves collisions with a linked list or tree, and resizes when its load threshold is exceeded; correct equals and hashCode implementations are mandatory.
Direct answer
What a strong answer covers
How it works
HashMap stores entries in an array of buckets indexed by a spread of the key’s hashCode. Keys with the same bucket form a linked list, which since Java 8 converts to a red-black tree once it holds more than eight entries, keeping worst-case lookups logarithmic instead of linear. When the number of entries exceeds capacity times the load factor of 0.75, the table doubles and every entry is rehashed. Average get and put are constant time only if hashCode distributes keys well and equals is consistent with it.
Example
Using a mutable object as a key and changing a field after insertion moves its hash but not its bucket, so map.get returns null for a key that is still inside the map. Pre-sizing a map with new HashMap<>(expected * 4 / 3 + 1) before loading 100,000 entries avoids several rehash passes during the bulk insert.
Common mistakes
- Overriding equals without hashCode, so equal keys land in different buckets.
- Expecting iteration order to be stable or insertion-ordered, which LinkedHashMap provides and HashMap does not.
- Sharing a HashMap between threads without synchronisation and corrupting it during a resize.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.