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

The Cantor Principle: Why the Contract Is Not Bidirectional

Learn why equal hash codes don't imply equality—multiple unequal objects can share the same hash code (collisions).

The Cantor Principle: Why the Contract Is Not Bidirectional

What you'll learn: You'll understand why equal hash codes don't guarantee object equality—only the reverse is true.

The One-Way Street

You've learned that the equals-hashCode contract requires: if two objects are equal, they must have the same hash code. But here's the crucial asymmetry: if two objects have the same hash code, they are NOT required to be equal.

This is called the Cantor Principle (named after set theory): the contract is one-directional, not bidirectional.

Why This Matters

Hash codes are typically int values, giving you roughly 4 billion possible values. But you might have trillions of possible objects in your domain. By the pigeonhole principle, multiple different objects must share the same hash code—these are called hash collisions.

The Filing Cabinet Analogy

Think of hash codes as drawer labels in a filing cabinet:

  • The contract says: Documents that are identical copies must go in the same drawer (equal objects → same hash code)
  • But: The same drawer can contain different documents (same hash code ≠ equal objects)

When you open drawer #42, you might find multiple unequal documents. Hash-based collections like HashMap use equals() to search within that drawer to find the exact match.

Practical Impact

String s1 = "Aa";
String s2 = "BB";
// These have the same hashCode (2112) but are NOT equal!

Hash-based collections rely on this principle: hash codes narrow down the search space quickly, then equals() does the final verification.

Key Takeaway: The equals-hashCode contract is unidirectional: equality guarantees identical hash codes, but identical hash codes don't guarantee equality—collisions are expected and handled by checking equals().