12 / 17

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

Equality and Hash Codes for Keys

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.

Difficulty: 3/10

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?