# Part 4.3 — HashMap Interview Questions (50+ Senior-Level)
These are the kinds of questions asked at companies such as Oracle, Amazon, Microsoft, Goldman Sachs, JPMorgan Chase, Walmart, SAP, and other product companies.
The goal is not to memorize answers but to understand the reasoning behind them.
Basic Questions¶
Q1. What is HashMap?¶
Answer:
HashMap is a hash table implementation of the Map interface that stores key-value pairs.
Features:
- Average O(1) lookup
- Allows one null key
- Allows multiple null values
- Not thread-safe
- Does not maintain insertion order
Q2. Why is HashMap fast?¶
Because it:
- Computes the hash.
- Calculates the bucket index.
- Searches only one bucket instead of the entire collection.
Average complexity:
O(1)
Q3. Why is HashMap not ordered?¶
The bucket location depends on the hash value, not the insertion sequence.
If insertion order is required:
LinkedHashMap
Q4. Difference between HashMap and Hashtable?¶
| HashMap | Hashtable |
|---|---|
| Not synchronized | Synchronized |
| Allows one null key | No null keys |
| Allows null values | No null values |
| Better performance | Slower |
| Introduced in JDK 1.2 | Legacy (JDK 1.0) |
Q5. Difference between HashMap and LinkedHashMap?¶
HashMap:
No ordering
LinkedHashMap:
Maintains insertion order
Internally:
Hash Table
+
Doubly Linked List
Q6. Difference between HashMap and TreeMap?¶
| HashMap | TreeMap |
|---|---|
| O(1) average | O(log n) |
| Unordered | Sorted |
| Hash table | Red-Black Tree |
| Allows one null key | Does not allow null keys with natural ordering |
Internal Questions¶
Q7. Why does HashMap use an array?¶
Arrays provide direct indexed access.
Index
↓
Bucket
Constant-time access to buckets.
Q8. Why are capacities powers of two?¶
So this works efficiently:
index = hash & (capacity - 1);
Instead of:
hash % capacity;
Q9. Why is the default load factor 0.75?¶
It provides a good balance:
- Lower load factor → fewer collisions but more memory.
- Higher load factor → more collisions but less memory.
0.75 is an empirically chosen compromise.
Q10. Why does Java mix hash bits?¶
h ^ (h >>> 16)
To improve bucket distribution, especially when the table size is small.
equals() and hashCode()¶
Q11. Which is called first?¶
hashCode()
↓
equals()
Always.
Q12. Why?¶
Hash code identifies the candidate bucket.
equals() is only used to compare keys within that bucket.
Q13. Can equal objects have different hash codes?¶
No.
That violates the contract.
Q14. Can different objects have the same hash code?¶
Yes.
This is a collision.
Q15. Why override both methods?¶
Overriding only one breaks hash-based collections.
equals()only → lookups fail.hashCode()only → duplicate logical keys.
Collision Questions¶
Q16. What is a collision?¶
Two different keys map to the same bucket.
Q17. How does HashMap resolve collisions?¶
Java 8:
Bucket
↓
Linked List
↓
Red-Black Tree
(if threshold reached)
Q18. When does treeification happen?¶
Both conditions must be true:
- Bucket size ≥ 8
- Table capacity ≥ 64
Q19. Why not treeify immediately?¶
Resizing a small table often distributes entries better, avoiding the need for a tree.
Q20. Why untreeify below 6?¶
To avoid repeated conversions between linked lists and trees (hysteresis).
Resize Questions¶
Q21. When does resize occur?¶
When:
size > threshold
Threshold:
capacity × loadFactor
Q22. Why is resize expensive?¶
Every entry must be redistributed.
Complexity:
O(n)
Q23. Does resize happen on every insertion?¶
No.
Only when the threshold is exceeded.
Q24. Why is insertion amortized O(1)?¶
Because expensive resizes happen infrequently.
Null Key Questions¶
Q25. Why only one null key?¶
null is always treated as the same key.
A second insertion replaces the previous value.
Q26. Where is the null key stored?¶
Conceptually, in bucket 0 because its hash is treated as 0.
Scenario-Based Questions¶
Q27.¶
map.put(1, "A");
map.put(1, "B");
Result?
1 → B
The value is replaced.
Q28.¶
map.put(null, "A");
map.put(null, "B");
Result?
null → B
Q29.¶
map.put(1, null);
Allowed?
Yes.
Q30.¶
map.get(2);
Key doesn't exist.
Returns:
null
This is why containsKey() is useful when null is a valid value.
Coding Scenario¶
Q31.¶
Employee e = new Employee(1);
map.put(e, "Alice");
e.setId(2);
map.get(e);
Why might this return null?
Because changing the key changes its hash code or equality, so the key is searched in a different bucket.
Threading Questions¶
Q32. Is HashMap thread-safe?¶
No.
Q33. What should be used instead?¶
ConcurrentHashMap
Q34. Why not use Hashtable?¶
It synchronizes every operation, limiting scalability.
ConcurrentHashMap uses finer-grained concurrency mechanisms.
Performance Questions¶
Q35. How can performance be improved?¶
- Choose a good initial capacity.
- Use immutable keys.
- Implement
hashCode()correctly. - Avoid excessive collisions.
Q36. Is HashMap always O(1)?¶
No.
Average:
O(1)
Worst case:
O(log n)
(after treeification)
Q37. What is the worst possible case?¶
If all keys map to one linked-list bucket and it is not treeified:
O(n)
Tricky Questions¶
Q38. Why doesn't HashMap use binary search?¶
Because entries are not globally sorted.
Q39. Can a HashMap contain duplicate values?¶
Yes.
Only keys must be unique.
Q40. Can keys be mutable?¶
Technically yes.
Should they be?
No.
Q41. Is String a good HashMap key?¶
Yes.
Because it is immutable and has a well-designed hashCode() implementation.
Q42. Is ArrayList a good key?¶
Only if it is not modified after insertion. Since ArrayList is mutable, it is generally a poor choice as a key.
Q43. Why are records good keys?¶
Records are immutable by design (assuming their components are immutable) and automatically implement equals() and hashCode().
Q44. Can hashCode() return a negative number?¶
Yes.
HashMap handles negative hash values correctly.
Q45. Can two different keys go into different buckets but still have the same hash code?¶
No.
The bucket index is derived from the hash value and the table capacity. Two keys with the same hash code will compute the same bucket index for a given capacity.
Q46. Can two different hash codes end up in the same bucket?¶
Yes.
Different hash values can produce the same bucket index after the bitwise masking operation.
Q47. Does HashMap call equals() for every key?¶
No.
Only for keys in the selected bucket.
Q48. Why doesn't HashMap compare values?¶
Because lookup is based on keys.
Values are not required to be unique.
Q49. What happens if hashCode() always returns 1?¶
Everything goes into one bucket.
Performance degrades toward:
O(n)
(or O(log n) after treeification).
Q50. Why is HashMap the default choice for lookups?¶
Because it provides:
- Fast average lookup
- Fast insertion
- Good memory/performance balance
- Flexible key types
Production Scenario 1¶
Problem:
Application performance degrades as data grows.
Possible causes:
- Poor
hashCode() - High collision rate
- Frequent resizing
- Mutable keys
- Inadequate initial capacity
Production Scenario 2¶
Problem:
map.get(key)
returns null, but you're certain the key was inserted.
Possible causes:
equals()/hashCode()contract is broken.- The key was mutated after insertion.
- You're using a different logical key without proper equality.
- The key was removed.
Production Scenario 3¶
Memory usage is unexpectedly high.
Possible reasons:
- Large numbers of entries.
- Oversized capacity.
- Large key/value objects.
- Holding references longer than necessary, preventing garbage collection.
Senior Interview Exercise¶
Consider:
Map<Employee, String> map = new HashMap<>();
Employee e1 = new Employee(1);
map.put(e1, "Alice");
Employee e2 = new Employee(1);
System.out.println(map.get(e2));
Question: Under what conditions does this print "Alice"?
Answer:
Employee must correctly override both:
equals()hashCode()
using the same logical fields (for example, id).
Final HashMap Checklist¶
You should now be able to explain:
- Internal bucket array
Nodestructure- Hash computation
- Bit spreading (
h ^ (h >>> 16)) - Bucket index calculation
- Collision handling
- Linked list vs red-black tree
- Treeification and untreeification thresholds
- Resizing and load factor
- Why capacities are powers of two
equals()/hashCode()contract- Mutable key pitfalls
- Java 7 vs Java 8 differences
- Average and worst-case complexities
- Common production issues and debugging strategies
If you can confidently answer the questions in this section and explain the reasoning—not just recite definitions—you'll be well prepared for most senior-level HashMap interview discussions.
Next: Part 5 — HashSet Deep Dive, where we'll examine why HashSet is implemented on top of HashMap, how duplicate detection works, internal implementation, performance characteristics, and common interview questions.