12 / 17

What is the significance of Equals() and GetHashCode() in C#/Java when using objects as keys?

Difficulty: 3/10

Equality and Hash Codes for Keys

When objects are used as Hash Table keys, equality and hashing must obey a consistent contract. In Java, if two objects are equal according to equals(), they must return the same hashCode(). In C#, Equals() and GetHashCode() must similarly agree: objects considered equal must have identical hash codes.

javascript
  1. 1

    Equal keys must produce equal hash codes.

  2. 2

    Unequal keys may still produce the same hash code because collisions are allowed.

  3. 3

    The fields used for equality and hashing should remain stable while the key is stored.

  4. 4

    Breaking the equality/hash contract can cause failed lookups or duplicate logical keys.

  5. 5

    When overriding equality, the corresponding hash implementation must also be updated.

Follow-up Questions

  • What happens if equals() is overridden without hashCode()?
  • Why are mutable fields dangerous in keys?
  • Can unequal objects have the same hash code?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.