Junior — Middle
Explain what happens when two keys in a HashMap have the same hash value and how it affects data storage?
sobes.tech AI
Answer from AI
When two keys in a HashMap have the same hash value, it is called a collision. HashMap uses a hash function to determine the index where to place the key-value pair. In case of a collision, both keys end up in the same bucket.
To resolve collisions, the following methods are usually used:
- Linked lists: all elements with the same hash are stored in a list within a single bucket. During search, elements of the list are iterated, comparing keys.
- Trees (e.g., red-black trees): in modern implementations (e.g., Java 8+), when there are many collisions, linked lists are converted into balanced trees to speed up search.
Thus, collisions affect the performance of insert and search operations, as instead of direct access by index, it is necessary to traverse the chain of elements. However, proper implementation and a good hash function minimize these cases.