How HashMap Works Inside
40 min · Intermediate
A HashMap is an array of buckets: the key's hashCode picks a bucket, and equals finds the right entry inside it. "How does HashMap work internally?" is the most asked Java collections question, and a clear step-by-step answer sets you apart.
Topics in this lesson
- put and get: hashCode, spreading and the bucket index
- Collisions: chains and Java 8 treeification
- Load factor 0.75, capacity and resizing
- null keys, and why keys should be immutable
- The two-minute model answer, plus follow-ups
Interview questions this lesson answers
- How does HashMap work internally?
- What is a hash collision and how does HashMap handle it?
- What is the load factor, and what happens when it is crossed?
- Why should HashMap keys be immutable?
- What happens if hashCode always returns the same value?
- Does HashMap allow null? What about Hashtable and ConcurrentHashMap?
- Why is the capacity always a power of two?
- Is HashMap thread-safe? What would you use instead?
- Why does HashMap still call equals after comparing hash codes?
- What does get return when a key is absent, and how do you tell that apart from a null value?
Sign in free to continue this lesson
Create a free account to read every lesson, practise with the exercises and keep track of your progress.