Return to site

What is the contract between equals() and hashCode() in Java?

August 4, 2025

๐Ÿš€ Java Interview Questions โ€“ Episode 6
๐Ÿ’ก What is the contract between equals() and hashCode() in Java?
๐Ÿ“ And where is it used?

In Java, whenever you override equals(), you must also override hashCode() โ€” this is known as the equals-hashCode contract. Hereโ€™s the rule:
โœ… If two objects are equal according to equals(), then they must have the same hashCode().
โŒ The reverse is not necessarily true: two objects with the same hashCode() arenโ€™t always equal.

๐Ÿ” Where is it used?
This contract is essential when working with collections like:
๐ŸŸฃ HashSet
๐ŸŸฃ HashMap
๐ŸŸฃ Hashtable
Without following this contract, your objects may behave unexpectedly in hash-based structures โ€” like being "lost" in a HashSet even though they seem equal. โš ๏ธ

๐Ÿ’ก Always override both methods together for correct behavior in hash-based collections.