Explain the equals() and hashCode() contract. What breaks if you get it wrong?
The contract
- Reflexive, symmetric, transitive, consistent, and
x.equals(null)is false. - If
a.equals(b)thena.hashCode() == b.hashCode(). The reverse is not required: unequal objects may share a hash code (a collision). hashCode()must return the same value while the fields used inequalsare unchanged.
What breaks
- Override equals but not hashCode: two equal objects land in different buckets, so
set.add(a); set.contains(copyOfA)returns false and you get duplicates in aHashSet. - Use mutable fields: the object "disappears" from a hash collection after a field changes.
- Asymmetric equals with inheritance: if
ColorPoint extends Pointand only one side checks color,p.equals(cp) != cp.equals(p), and collections behave unpredictably.
How to implement in practice
- Prefer records for value objects; the compiler generates correct
equals,hashCodeandtoStringfrom all components. - For JPA entities, base equality on a stable business key or the identifier, and handle the transient state (id is null before persist). A common pattern is
getClass()-safe equality on id with a constanthashCode()so the hash does not change when the id is assigned. - Use
Objects.equalsandObjects.hash, and decide deliberately betweeninstanceof(allows subclasses, risks symmetry) andgetClass()(strict, breaks Liskov for proxies such as Hibernate's).
Example
public record Money(BigDecimal amount, String currency) {
public Money {
amount = amount.stripTrailingZeros(); // 1.0 and 1.00 must be equal
}
}BigDecimal.equals compares scale, so new BigDecimal("1.0").equals(new BigDecimal("1.00")) is false. Normalising in the compact constructor keeps the record's generated equals meaningful.
Follow-up questions interviewers ask
Try answering each one before you open it.
Can two unequal objects have the same hashCode? Is that a problem?
Yes, that is a collision and it is legal. Both entries go to the same bucket and equals distinguishes them. It only becomes a problem when it happens a lot: a hashCode() that returns a constant turns a HashMap into a linked list (or a tree in Java 8+), degrading performance from O(1) to O(n) or O(log n).
Should equals() use instanceof or getClass()?
instanceof lets a subclass instance equal a superclass instance, which is what you want when subclasses do not add state (and it works with Hibernate proxies). getClass() is strict and keeps symmetry when subclasses add fields, but breaks for proxies and violates Liskov. A practical rule: make value classes final (or records) and use instanceof, and avoid adding equality-relevant state in subclasses.
How would you implement equals and hashCode for a JPA entity?
Use the database id, but guard the transient state:
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Order other)) return false;
return id != null && id.equals(other.getId());
}
@Override public int hashCode() { return getClass().hashCode(); }A constant hash per class looks odd but keeps the hash stable before and after persist() assigns the id, so an entity added to a HashSet before saving can still be found afterwards. Use other.getId() rather than the field so lazy proxies initialise correctly.