1.Explain the contract between equals() and hashCode() in Java. What breaks if you override one but not the other?
Warm-upWhat a strong answer covers
- equals() defines logical equality; hashCode() returns an int used to bucket objects in hash-based collections
- The contract: equal objects must return equal hash codes, and hashCode should be consistent across calls while the object is unchanged
- If you override equals() but not hashCode(), two logically equal objects can land in different buckets, so a HashMap or HashSet fails to find or de-duplicate them
- Both should be built from the same immutable, identity-defining fields; Objects.equals and Objects.hash make correct implementations easy
Where people lose the point
- Claiming equal hash codes imply equal objects (collisions are allowed and expected)
- Including mutable fields in the calculation, which corrupts the object's location in a hash collection when the field changes
- Forgetting the null and type checks in equals(), or using == on object fields instead of Objects.equals