Sobes.tech
Junior — Middle

What happens when two keys receive the same hash code in HashMap?

sobes.tech AI

Answer from AI

When two keys in a HashMap have the same hash code, a collision occurs. HashMap resolves this issue by placing both elements in the same bucket. Inside the bucket, elements are stored as a linked list or, starting from a certain version of Java, as a balanced tree (TreeNode) to improve performance.

When adding a new key with the same hash code, HashMap iterates through the elements in the bucket and compares keys using the equals() method. If the key already exists, the value is updated; if not, a new element is added to the structure within the bucket.

Example:

Map<String, String> map = new HashMap<>();

// Suppose "Aa" and "BB" have the same hash code
map.put("Aa", "Value1");
map.put("BB", "Value2");

// Both keys will be stored in the same bucket, but as different entries
What happens when two keys receive the same hash code… - sobes.tech