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

The equals-hashCode Contract in Detail

Learn the precise rule: if a.equals(b), then a.hashCode() must equal b.hashCode().

The equals-hashCode Contract in Detail

You'll learn the precise rule that governs the relationship between equals() and hashCode() in Java.

The Golden Rule

The equals-hashCode contract has one ironclad requirement:

If two objects are equal according to equals(), they MUST produce the same hashCode().

In code terms: if a.equals(b) returns true, then a.hashCode() MUST equal b.hashCode().

Why This Rule Exists

Hash-based collections like HashMap and HashSet rely on this guarantee. They use hashCode() to quickly narrow down where an object might be stored (the "bucket"), then use equals() to confirm identity within that bucket.

If you break this contract—if two equal objects produce different hash codes—those objects will land in different buckets. The collection won't find them even though they're logically equal. You've seen this bug in action in the previous lessons.

The Reverse Is NOT Required

Notice the contract only goes one direction:

  • Equal objects → same hash code ✓ REQUIRED
  • Same hash code → equal objects? NOT required

Multiple unequal objects can share the same hash code (this is called a "collision" and is perfectly legal). The contract doesn't force uniqueness.

Practical Implication

When you override equals(), you must override hashCode() to maintain this contract. If you forget, equal objects might have different hash codes, breaking every hash-based collection you use.

Key Takeaway: The equals-hashCode contract mandates that equal objects produce identical hash codes, ensuring hash-based collections work correctly—but the reverse (same hash code implies equality) is not required.