skip to content

equals() & hashCode()

The equals and hashCode contracts and why they must be overridden together: the five equals properties, the equal-implies-equal-hash rule, the getClass versus instanceof choice, and the effect on HashMap and HashSet. This is one of the most frequently asked Java questions at any level, because getting it wrong silently corrupts collections.

part ofJavaoverview, primer and where to startread it →
on this pageshow

questions

5

What are the five properties the equals() contract requires (reflexive, symmetric, transitive, consistent, non-null), and what is a common way to violate symmetry/transitivity?

level: middleimportance: must knowfreq 70%

basics

~20 s

equals() must be reflexive (x equals itself), symmetric (if x equals y then y equals x), transitive (if x=y and y=z then x=z), consistent (same result if nothing changes), and return false for null. Mixing a class with its subclass in equals() often breaks symmetry or transitivity.

open as a page

How do Java records implement equals()/hashCode(), and how would you write a correct manual implementation for a non-record value class?

level: middleimportance: should knowfreq 50%

basics

~20 s

A record auto-generates equals() and hashCode() from all its components, so equal field values mean equal objects. For a regular class, compare each significant field with Objects.equals() in equals(), and combine the same fields with Objects.hash() in hashCode().

open as a page

In equals(), when should you use getClass() versus instanceof for the type check, and what are the tradeoffs?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Use instanceof for flexibility — it lets compatible types compare and is null-safe — but only if subclasses don't add fields that affect equality. Use getClass() for strict 'exactly the same class' equality, at the cost that a subclass can never equal its parent.

open as a page

Why is using a mutable object as a HashMap key (or HashSet element) dangerous, and how does this relate to equals()/hashCode()?

level: seniorimportance: should knowfreq 55%

basics

~20 s

A hash collection records an object's hashCode() when you add it. If you then mutate a field used by hashCode(), the object's bucket changes, so the collection looks in the old bucket and can no longer find it. Use immutable keys.

open as a page