Course contentsShow
← Java
Lesson 1085 of 2,87025. Set ImplementationsFree lesson

The Contract Between equals and hashCode

Learn the fundamental rule: equal objects must have equal hash codes, or Sets will fail silently.

The Contract Between equals and hashCode

What you'll learn: You'll understand the critical rule that equal objects must always produce equal hash codes, or hash-based collections will break silently.

The Fundamental Rule

When you override equals() in a class, you must also override hashCode() to maintain a crucial contract: if two objects are equal according to equals(), they must return the same hash code from hashCode().

This isn't a suggestion—it's a requirement that hash-based collections like HashSet depend on absolutely.

Why This Contract Exists

Think of HashSet as a library with numbered shelves (buckets). When you add an object, hashCode() determines which shelf it goes on. Later, when you check if the set contains an object, HashSet:

  1. Calls hashCode() to find the right shelf
  2. Only then uses equals() to verify the exact object

If two equal objects produce different hash codes, they'll be placed on different shelves. When you search for one, you'll look on the wrong shelf and won't find it—even though it's in the set!

The Silent Failure

This is particularly dangerous because your code won't crash. It just quietly returns the wrong answer. Your HashSet might contain duplicates, or contains() might return false when the element is actually present.

The reverse isn't required: unequal objects can have the same hash code (a collision), and that's fine—the collection handles it. But equal objects with different hash codes violates the contract and breaks everything.

Key Takeaway: Always override hashCode() when you override equals(), ensuring equal objects produce identical hash codes. Breaking this contract causes hash-based collections to malfunction silently.