Course contentsShow
← Java
Lesson 542 of 2,87013. The Object Class and Common MethodsFree lesson

Overriding equals: The Five Requirements

Learn the reflexive, symmetric, transitive, consistent, and non-nullity requirements that every equals implementation must satisfy.

Overriding equals: The Five Requirements

You'll learn: The five mandatory properties every equals method must satisfy to create a correct, predictable equality comparison.

Why These Requirements Matter

When you override equals, you're not just writing any comparison method—you're creating a contract that the entire Java ecosystem relies on. Collections, frameworks, and other Java code assume your equals method behaves consistently according to five strict rules.

Think of these requirements like traffic laws: everyone must follow them for the system to work safely.

The Five Requirements

1. Reflexive

Any object must equal itself: x.equals(x) must always return true.

2. Symmetric

If x.equals(y) returns true, then y.equals(x) must also return true. The relationship works both ways.

3. Transitive

If x.equals(y) and y.equals(z) are both true, then x.equals(z) must be true. Equality chains properly.

4. Consistent

Multiple calls to x.equals(y) must consistently return the same result (assuming neither object was modified). No randomness or time-based changes.

5. Non-Nullity

For any non-null reference x, calling x.equals(null) must return false. Objects never equal null.

Why Each Rule Exists

Reflexive ensures objects work in collections that check self-equality. Symmetric prevents confusing situations where order matters. Transitive allows you to group equivalent objects reliably. Consistent ensures predictable behavior. Non-nullity prevents null-handling bugs.

Violating any of these rules causes subtle bugs in HashSet, HashMap, sorting algorithms, and anywhere equality is checked.

Key Takeaway: Every equals implementation must be reflexive, symmetric, transitive, consistent, and return false for null comparisons—these five requirements form the fundamental contract your code must honor.