How does HashMap work internally, and what happens when it resizes?
HashMap stores entries in an array of buckets indexed by a hash of the key; collisions chain into a linked list that converts to a red-black tree past a threshold, and exceeding the load factor triggers a resize that reallocates and redistributes every entry. It also connects collections to the point an interviewer is testing.
Answer
Short answer
HashMap works by hashing the key to choose a bucket, then comparing keys with equals() inside that bucket. Collisions are stored as a linked list and can treeify in Java 8+, while resizing doubles capacity and redistributes entries, so bad hashCode/equals or missing initial capacity shows up as lookup and resize cost.
Was this answer helpful?
Likely follow-ups
- Why is the default capacity 16 and the load factor 0.75?
- What breaks if a key object is mutated after being inserted?
- How does ConcurrentHashMap achieve thread safety without locking the whole map?
- Why did Java 8 introduce treeification, and what problem did it solve?
Related questions
- Sorting a list throws IllegalArgumentException saying the comparison method violates its general contract. What did the comparator get wrong?mediumAlso on collections5 min
- Count the subarrays whose elements sum to k, where the values may be negative.mediumAlso on hashing4 min
- Product companies hiring final-year students: what difficulty of coding round should you expect, and how do you calibrate your practice?mediumAlso on data-structures5 min
- You are applying for a first- or second-year internship and have no experience. What does the interview expect you to know?easyAlso on data-structures4 min