Sobes.tech
Junior — Middle

What happens if you try to insert two objects considered equal by equals but with different hashCode values into a HashMap?

sobes.tech AI

Answer from AI

If two objects are considered equal by the equals() method but have different hashCode() values, then inserting them into a HashMap will behave incorrectly.

Why?

  • HashMap first uses hashCode() to determine the bucket where the object should be placed.
  • Then, within the bucket, it compares objects using equals() to check for key equality.

If hashCode() for equal objects differs, they will go into different buckets, and HashMap will not be able to detect that the key already exists.

As a result:

  • Duplicate keys may appear in the HashMap, violating the collection's contract.
  • Searching by key may not find an object even if it exists, because hashCode() does not match.

Example:

class Key {
    private int id;

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Key)) return false;
        Key key = (Key) o;
        return id == key.id;
    }

    @Override
    public int hashCode() {
        return id + 1; // Error: for equal objects, hashCode should be the same
    }
}

If equals considers two objects equal (e.g., id=1), but hashCode returns different values, HashMap will not work correctly.

Therefore, it is important to follow the contract: if equals(a, b) == true, then hashCode(a) == hashCode(b).