Objects compared by reference with ==. equals defines value equality; hashCode supports hash-based collections. Override both together with a consistent contract.
Contract (simplified)
- If
a.equals(b), thena.hashCode() == b.hashCode() - Reflexive, symmetric, transitive, consistent equals
Records (Java 16+)
record Point(int x, int y) {} generates equals, hashCode, and toString automatically—prefer for data carriers.
Important interview questions and answers
- Q: Why override hashCode with equals?
A: HashMap/HashSet break if equal objects hash differently. - Q: Default equals behavior?
A: Inherited from Object—reference equality like==.
Self-check
- What happens if two equal objects have different hash codes?
- When should you use a record instead of a class?