Middle
When does a hashCode collision occur in HashMap?
sobes.tech AI
Answer from AI
A hashCode collision in HashMap occurs when two different keys return the same hashCode value. In this case, both keys end up in the same bucket of the internal HashMap structure.
HashMap uses hashCode to determine the index of the bucket where the key-value pair is stored. If the hashCodes match, the keys are stored in the same chain (or tree, if there are many elements) within that bucket.
Collisions are inevitable due to the limited range of int (32-bit) for hashCode and the potentially large number of unique keys. A good hashCode implementation minimizes collisions, but it is impossible to completely avoid them.
Example:
String a = "FB"; // hashCode = 2236
String b = "Ea"; // hashCode = 2236
System.out.println(a.hashCode()); // 2236
System.out.println(b.hashCode()); // 2236
HashMap<String, Integer> map = new HashMap<>();
map.put(a, 1);
map.put(b, 2); // both keys will go into the same bucket due to identical hashCode