Sobes.tech
Junior — Middle

What happens if multiple objects with the same hashCode result are added to a HashMap?

sobes.tech AI

Answer from AI

If you add multiple objects with the same hashCode value to a HashMap, they will be placed in the same bucket within the HashMap data structure. HashMap uses hashCode to determine the bucket index, but to distinguish keys within a single bucket, it calls the equals method.

Process:

  1. The hashCode of the key is computed to determine the bucket.
  2. Elements in the bucket are iterated over, and equals is called to compare with the new key.
  3. If equals returns true — the value is updated (overwritten).
  4. If equals returns false — the new element is added to the bucket as a separate entry.

Thus, having the same hashCode does not mean the keys are equal. HashMap handles collisions correctly by using equals for exact comparison.

Example:

Map<Key, String> map = new HashMap<>();
Key key1 = new Key(1); // hashCode = 42
Key key2 = new Key(2); // hashCode = 42, but key1.equals(key2) == false
map.put(key1, "value1");
map.put(key2, "value2");
// The map will contain both keys with different values

Where the Key class overrides hashCode to return the same value, but equals distinguishes the objects.