CodingNeed.
Fresher · Language concepts

Equals and HashCode Contract

Explain the equals/hashCode contract. Describe what happens when a key changes after insertion into a HashMap.

Examples

Compare approaches

Baseline approach

Begin by explaining the core mechanism, stating assumptions, and walking through one concrete example.

Time: Depends on design · Space: Depends on design

// Define an immutable key with consistent equals and hashCode.
Strong answer

Equal objects must have equal hashes. Unequal objects may collide. Mutable fields used in hashing can make an inserted key unreachable by ordinary lookup.

Time: Discuss operation costs · Space: Discuss retained state

// Define an immutable key with consistent equals and hashCode.

Common traps

  • Reference equality and value equality are different.
  • State assumptions and justify trade-offs rather than memorizing a single answer.
Practise in the workspace →