01 / 20
\(==\)
#code

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.

Java

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?

a b Object @1a2b "Alice", 25 Object @3c4d
\(a == b\) ?
false

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.

Without Override
new Student("Ada") and new Student("Ada") are not equal because they are distinct heap objects.
With Override
new Student("Ada").equals(new Student("Ada")) returns true because we compare the name field.

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.

"Ada" hashCode(): 7
hash \(\%\) 4
Bucket 0 Bucket 1 Bucket 2 Bucket 3 "Ada" "Bob" "Eve" HashMap internal array

The equals-hashCode Contract

1
If a.equals(b) is true, then a.hashCode() must equal b.hashCode().
2
If a.hashCode() \(\neq\) b.hashCode(), then a.equals(b) must be false.
3
If a.hashCode() \(==\) b.hashCode(), a.equals(b) may be true or false (collisions are allowed).

What Breaks Without It

1. map.put(key1, "Hello") key1: hash=5 Bucket 5 "Hello" 2. map.get(key2) key2: hash=9 equals(key1) = true Bucket 9 empty! Returns null! key1.equals(key2) = true, but hash codes differ → HashMap looks in the wrong bucket → value is lost

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()

1
Check for self-reference: if (this \(==\) obj) return true;
2
Null guard: if (obj \(==\) null) return false;
3
Type check: if (getClass() \(\neq\) obj.getClass()) return false;
4
Cast: MyClass other = (MyClass) obj;
5
Compare fields: return Objects.equals(field1, other.field1) \(&&\) field2 \(==\) other.field2;

Example: equals() for Student

@Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Student other = (Student) obj; return Objects.equals(name, other.name) && age == other.age; }

How to Override hashCode()

1
Base it on the same fields as `equals()`. Never use a field in `hashCode()` that isn't used in `equals()`.
2
Use Objects.hash() for a quick, correct implementation: return Objects.hash(field1, field2);
3
Or compute manually: multiply a running result by a prime (31) and add each field's hash code.
@Override public int hashCode() { return Objects.hash(name, age); }

Complete Student Class

public class Student { private String name; private int age; @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; Student other = (Student) obj; return age == other.age && Objects.equals(name, other.name); } @Override public int hashCode() { return Objects.hash(name, age); } }

Testing with HashSet

Student s1 = new Student("Ada", 17); Student s2 = new Student("Ada", 17); Set<Student> set = new HashSet<>(); set.add(s1); set.add(s2); System.out.println(s1.equals(s2)); // true System.out.println(set.size()); // 1 (no duplicate!)
s1 s2 same hash Bucket N "Ada", 17 size = 1 duplicate rejected

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

@Override public int hashCode() { int result = 17; // non-zero seed result = 31 * result + (name != null ? name.hashCode() : 0); // String field result = 31 * result + age; // int field return result; }
Why 31?
31 is an odd prime. The JVM can optimize \(31 \times x\) as \((x \ll 5) - x\), making it fast.
Why 17?
Any non-zero starting value works. It helps distinguish objects where early fields are zero or null.

Common Mistakes

✕ Override one, not both
Overriding equals() without hashCode() breaks all hash-based collections.
✕ Wrong parameter type
Writing equals(Student obj) instead of equals(Object obj) creates an overload, not an override.
✕ Mutable hash fields
If a field used in hashCode() changes after insertion, the object becomes unreachable in the map.

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?