Sobes.tech
Junior — Middle

When does a situation occur in HashMap where two keys have the same hash and cause a collision?

sobes.tech AI

Answer from AI

A collision in HashMap occurs when two different keys have the same hash code value, and consequently, fall into the same bucket of the internal array. This happens because HashMap uses the hash code of the key to determine the index in the array where the key-value pair will be stored.

For example, if two key objects' hashCode() method returns the same number, then when added to the HashMap, they will end up in the same bucket. To resolve the collision, HashMap stores elements as a linked list (or a tree if there are many elements) within that bucket and searches through them, comparing keys using the equals() method.

Example:

String key1 = "FB"; // hashCode() == 2236
String key2 = "Ea"; // hashCode() == 2236

HashMap<String, Integer> map = new HashMap<>();
map.put(key1, 1);
map.put(key2, 2); // collision, both keys have the same hashCode

System.out.println(map.get("FB")); // 1
System.out.println(map.get("Ea")); // 2

Here, "FB" and "Ea" are a well-known example of strings with the same hash code, leading to a collision.

When does a situation occur in HashMap where two keys… - sobes.tech