Overriding
equals() & hashCode()
Learn why Java demands these two methods stay consistent, how to implement them correctly, and what breaks when they don't agree.
What is Object Identity?
By default, Java's \(==\) operator and the inherited Object.equals() both check reference identity: do two variables point to the exact same object in memory?
Why Override equals()?
Most real-world classes need logical equality: two objects are "equal" when their meaningful fields match, not when they occupy the same memory address.
What is hashCode()?
hashCode() returns an integer that hash-based collections use to decide which bucket an object belongs in. Think of it as a filing cabinet index.
The equals-hashCode Contract
What Breaks Without It
equals() vs \(==\)
| equals() | \(==\) | |
|---|---|---|
| Compares | Logical content (overridable) | Memory address (reference) |
| Default behavior | Same as \(==\) (inherited from Object) | Always reference check |
| Overridable? | Yes | No |
| Used by collections | Yes (contains, remove, get) | No |
| Primitives | N/A (only objects) | Compares values |
How to Override equals()
Example: equals() for Student
How to Override hashCode()
Complete Student Class
Testing with HashSet
instanceof vs getClass()
| instanceof | getClass() | |
|---|---|---|
| Subclass match? | Yes: Parent.equals(Child) can be true | No: strict same class only |
| Symmetry risk | High: a.equals(b) may differ from b.equals(a) | Safe: always symmetric |
| Best for | Final classes, or Liskov-aware designs | Classes that may be subclassed |
Manual hashCode() Recipe
Common Mistakes
Question 1 of 5
If a.equals(b) returns true, which statement must also be true according to the contract?
Question 2 of 5
A class overrides equals() using name and age, but its hashCode() only uses name. What can go wrong?
Question 3 of 5
What is the correct parameter type for a properly overridden equals() method?
Question 4 of 5
Which utility method provides a null-safe way to compute hashCode() from multiple fields?
Question 5 of 5
You add a Student to a HashSet, then change the student's name. When you call set.contains() with the same Student reference, what happens?