midJava

What is equals and hashCode contract?

Updated May 6, 2026

Short answer

Equal objects must have same hashCode.

Deep explanation

Used in hashing structures like HashMap to ensure correct key retrieval.

Real-world example

Ensures correct retrieval in HashSet.

Common mistakes

  • Overriding equals without hashCode.

Follow-up questions

  • What happens if contract is broken?
  • Why override both?

More Java interview questions

View all →