Junior — Middle
What happens inside a HashMap when two keys lead to the same hash bucket?
sobes.tech AI
Answer from AI
When two different keys in a HashMap have the same hash code and fall into the same hash bucket, a collision occurs. In Java HashMap, this is handled as follows:
- The bucket stores a linked list (or a tree if there are many elements).
- When adding a new element with the same hash code, the keys are compared using the
equals()method. - If the key already exists, the value is updated.
- If the key does not exist, the new element is added to the list in that bucket.
Starting from Java 8, if a bucket contains too many elements (usually more than 8), the linked list is transformed into a balanced tree (TreeNode), which improves search performance from O(n) to O(log n).
Thus, HashMap effectively handles collisions, ensuring correct storage and retrieval of elements.