What You'll Learn
You'll discover why compareTo must return zero exactly when equals returns true to avoid bizarre bugs in sorted collections.
The Core Principle
When you implement Comparable, your compareTo method should be consistent with equals. This means:
- If
a.equals(b)returnstrue, thena.compareTo(b)must return0 - If
a.compareTo(b)returns0, thena.equals(b)should returntrue(strongly recommended)
When these two methods disagree, sorted collections like TreeSet and TreeMap behave unpredictably—they rely on compareTo for ordering and equality checks, essentially ignoring your equals method.
Why This Matters
Imagine a Person class that compares by age in compareTo but checks name equality in equals:
public class Person implements Comparable<Person> {
String name;
int age;
public int compareTo(Person other) {
return this.age - other.age; // Only considers age
}
public boolean equals(Object o) {
Person p = (Person) o;
return this.name.equals(p.name); // Only considers name
}
}
Now create two people: Alice (age 30) and Bob (age 30). Here's the problem:
alice.equals(bob)→false(different names)alice.compareTo(bob)→0(same age)
A TreeSet would treat them as duplicates and refuse to add both! A HashSet would store both. Same objects, different behavior—inconsistent.
The Fix
Make both methods examine the same fields for comparison and equality. If age determines order, it should also determine equality—or compare additional fields as tiebreakers in compareTo.
Key Takeaway: Always ensure compareTo returns zero if and only if equals returns true; otherwise sorted collections will produce confusing, incorrect results.