Sobes.tech
Junior — Middle

What happens inside a HashMap when a collision of keys occurs during insertion?

sobes.tech AI

Answer from AI

In Java, HashMap first computes the hash code of the key when inserting an element, then determines the index in the bucket array. If there is already an element in that bucket (collision), HashMap uses linked lists (chains) to store multiple elements with different keys but the same index.

Starting from Java 8, if the length of the chain exceeds a certain threshold (usually 8), the linked list is converted into a balanced tree (red-black tree) to speed up search and insertion.

Thus, in case of collision, new elements are added to the chain or tree in the corresponding bucket, which allows efficient storage and retrieval of elements even when hashes match.

What happens inside a HashMap when a collision of… - sobes.tech