What is the contract between equals and hashCode, and why must two 'equal' objects produce the same hash code?

Last updated 5 July 2026

  • Contract: objects equal under equals() must return the same hashCode(). Unequal objects may collide but ideally shouldn't.

  • Why: a HashMap picks a bucket by hash first, then checks equals(). Equal objects with different hashes land in different buckets and lookups fail.

  • Always override both using the same fields, and never hash on fields you mutate while the object is in a hash-based collection.

  • https://www.tutorialspoint.com/article/what-is-the-contract-between-equals-and-hashcode-methods-in-java
All Object-Oriented Programming interview questions