Junior
What is a hash code collision in the context of HashMap?
sobes.tech AI
Answer from AI
Hash code collisions in HashMap occur when two unequal objects have the same hash code (hashCode()).
When adding an object to a HashMap, if its hash code matches the hash code of an object already present in the same bucket, the HashMap resolves the collision by calling the equals() method to compare the keys.
- If
equals()returnstrue, the new object replaces the old one (if the keys are equal). - If
equals()returnsfalse, both objects (with different keys but the same hash code) are stored in the same bucket, forming either a linked list or a tree (starting from Java 8 when the number of elements in the bucket is sufficient), depending on the number of elements in the bucket.
Frequent collisions degrade the performance of HashMap, reducing the complexity of get() and put() operations from O(1) in the ideal case to O(n) in the worst case (for a list) or O(log n) (for a tree). Effective distribution of hash codes is key to the performance of HashMap.