Sub topic 3
The rules a comparison must follow
This chapter assumes you know Java generics, lambdas, and the basics of equals and hashCode. You should also have seen Comparable.compareTo and Comparator.compare at the signature level. Here you learn the rules both methods must obey, why sorting code relies on them, and how a violation shows up.
Why rules exist at all
compareTo and compare return an int. The sign of that number is the only thing callers use. A negative number means the first argument comes first, zero means the two are tied, and a positive number means the first argument comes second.
Sorting algorithms, TreeSet, TreeMap, PriorityQueue and Collections.binarySearch all make decisions from these signs. They assume the answers describe one consistent ordering. If your method says A < B, B < C and C < A, no sorted arrangement exists. The library does not detect this. It produces some arrangement, or fails in a way that depends on the data.
The Javadoc for Comparable states the contract. Comparator.compare follows the same rules. Write sgn(n) for the sign of n: -1, 0 or 1.
| Rule | Statement | What it protects |
|---|---|---|
| Antisymmetry | `sgn(x.compareTo(y)) == -sgn(y.compareTo(x))` for all `x`, `y` | Swapping the arguments flips the answer |
| Transitivity | If `x > y` and `y > z`, then `x > z` | Sorted order can exist at all |
| Tie consistency | If `x.compareTo(y) == 0`, then `sgn(x.compareTo(z)) == sgn(y.compareTo(z))` for every `z` | Tied elements are interchangeable |
| Exceptions | `x.compareTo(y)` throws the same exceptions in both directions | Predictable failure |
| Null | `x.compareTo(null)` throws `NullPointerException` | Null is never a valid argument for `Comparable` |
| Equals (recommended) | `x.compareTo(y) == 0` should match `x.equals(y)` | Sorted collections behave like other collections |
The first five are requirements. The last is a strong recommendation, and the Javadoc says to document any exception to it.
Antisymmetry
If a.compareTo(b) is negative, b.compareTo(a) must be positive. The two answers must also agree in sign when they are zero. An asymmetric comparison makes the result depend on which element the algorithm happened to put first.
The most common cause is a comparison written by hand with a mistake in one branch. Another is subtraction that overflows, covered below.
Transitivity
Transitivity has three parts:
- If
x < yandy < z, thenx < z. - If
x > yandy > z, thenx > z. - If
x == yandy == z, thenx == z. Here==means the comparison returns 0.
The third part is the one people break. A comparison that treats two values as equal when they are "close enough" is not transitive. 1.0 is close to 1.4, and 1.4 is close to 1.8, but 1.0 is not close to 1.8. Tolerance-based comparison does not form an ordering.
Tie consistency
If two objects compare as 0, they must also compare identically against everything else. This is what makes a tie mean "interchangeable for ordering purposes". A comparator that returns 0 for x and y but ranks x below z and y above z breaks the same assumption as the tolerance example.
Null and type errors
compareTo is called on a non-null receiver, so a null argument has no sensible answer. The contract requires NullPointerException:
public class NullCompare {
public static void main(String[] args) {
try {
"abc".compareTo(null);
} catch (NullPointerException e) {
System.out.println("compareTo(null) throws NullPointerException");
}
}
}A Comparator has more freedom. Its Javadoc allows it to define an order for null, which is how Comparator.nullsFirst works. A later chapter covers this.
A type mismatch gives a ClassCastException. A TreeSet that holds elements that are not Comparable, with no comparator supplied, fails on the first insertion:
import java.util.Set;
import java.util.TreeSet;
public class NotComparable {
public static void main(String[] args) {
Set<Object> set = new TreeSet<>();
try {
set.add(new Object());
} catch (ClassCastException e) {
System.out.println("Object is not Comparable: " + e.getMessage());
}
}
}TreeMap.put compares the first key with itself, which is why the failure appears on the first add and not on the second.
Seeing violations: a contract checker
The checker below tests the first three rules by brute force on a small sample. It is a debugging aid, not a proof, since a passing sample says nothing about inputs you did not include. It is still worth running against a new comparator.
import java.util.Comparator;
import java.util.List;
public class ContractChecker {
static <T> void check(String label, Comparator<T> cmp, List<T> samples) {
boolean ok = true;
for (T x : samples) {
for (T y : samples) {
if (Integer.signum(cmp.compare(x, y)) != -Integer.signum(cmp.compare(y, x))) {
System.out.println(label + ": antisymmetry violated for " + x + ", " + y);
ok = false;
}
if (cmp.compare(x, y) == 0) {
for (T z : samples) {
if (Integer.signum(cmp.compare(x, z)) != Integer.signum(cmp.compare(y, z))) {
System.out.println(label + ": tie inconsistency for "
+ x + ", " + y + " against " + z);
ok = false;
}
}
}
for (T z : samples) {
if (cmp.compare(x, y) > 0 && cmp.compare(y, z) > 0 && cmp.compare(x, z) <= 0) {
System.out.println(label + ": transitivity violated for "
+ x + " > " + y + " > " + z);
ok = false;
}
}
}
}
if (ok) {
System.out.println(label + ": no violations found in the sample");
}
}
public static void main(String[] args) {
Comparator<Integer> subtraction = (a, b) -> a - b;
Comparator<Integer> safe = Integer::compare;
Comparator<Double> tolerance =
(a, b) -> Math.abs(a - b) < 0.5 ? 0 : Double.compare(a, b);
List<Integer> ints = List.of(Integer.MAX_VALUE, -1, 0, 5);
List<Double> doubles = List.of(1.0, 1.4, 1.8);
check("subtraction", subtraction, ints);
check("Integer.compare", safe, ints);
check("tolerance", tolerance, doubles);
}
}The subtraction comparator fails antisymmetry. Integer.MAX_VALUE - (-1) overflows to a negative number, so the comparator says MAX_VALUE < -1. In the other direction, -1 - Integer.MAX_VALUE equals Integer.MIN_VALUE, which is also negative. Both directions return a negative result. Integer.compare reports no violations. The tolerance comparator is flagged for tie inconsistency: 1.0 and 1.4 tie, but they compare differently against 1.8.
What breaks when you violate the contract
The effect depends on the algorithm, which makes these bugs hard to find.
List.sort,Collections.sort,Arrays.sorton objects. These use TimSort. With about 32 or more elements it may detect an inconsistency while merging and throwIllegalArgumentException: Comparison method violates its general contract!. It does not always detect one. Small lists and lucky data sort without any error, in an order that is only partly correct.TreeSetandTreeMap. The tree navigates by comparison. If the comparison is inconsistent,containsandgetcan miss elements that were inserted, andremovecan fail to remove them.PriorityQueue. The heap property can fail.pollthen returns elements out of order, with no exception.Collections.binarySearch. It may return a wrong index or a false negative.
The same input can behave differently as the list grows. A comparator that passes your unit tests on ten elements can throw in production on a thousand.
Consistency with equals
The recommended rule is that x.compareTo(y) == 0 holds exactly when x.equals(y) is true. An ordering that satisfies this is called consistent with equals.
Sorting does not care. Sorted collections do. TreeSet and TreeMap decide whether two elements are duplicates using the comparison, never equals. If compareTo returns 0 for two objects that equals considers different, the second one is silently dropped by a TreeSet.
BigDecimal is the standard example. new BigDecimal("1.0") and new BigDecimal("1.00") differ under equals because their scales differ. They tie under compareTo. A HashSet holds both. A TreeSet holds one.
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;
public class ConsistencyDemo {
public static void main(String[] args) {
BigDecimal a = new BigDecimal("1.0");
BigDecimal b = new BigDecimal("1.00");
Set<BigDecimal> hash = new HashSet<>(Set.of(a, b));
Set<BigDecimal> tree = new TreeSet<>(Set.of(a, b));
System.out.println(hash.size()); // 2, because equals sees different scales
System.out.println(tree.size()); // 1, because compareTo returns 0
}
}This does not violate the contract. The contract only recommends consistency. The Javadoc asks that classes with an inconsistent ordering say so in their documentation. A later chapter returns to this in detail. For now, treat it as a decision to make on purpose.
A checklist for writing a comparison
- Compare with the box type's
comparemethod, or withComparator.comparingIntand similar factories. Never subtract. - Compare the most significant field first. Fall through to the next field only when the previous one returns 0.
- Return the result of the last comparison directly. Do not return only -1 or 1 from your own
ifchains unless you have handled the equal case. - Do not mix in state that can change between calls, such as a random number, a timestamp, or a field being modified by another thread.
- Decide whether the ordering should match
equals. If it should not, document it. - Never use floating-point tolerance as a tie rule.
Mutable fields deserve special care. If an object sits inside a TreeSet and a field used by its comparison changes, the tree is now ordered by stale information. The object is still stored, but lookups may not find it. Compare only on fields that do not change while the object is in a sorted collection.
Exercise
A comparator is written as (a, b) -> a.getScore() - b.getScore(), where getScore() returns an int and scores can range from -2,000,000,000 to 2,000,000,000. Which contract rule can it break, and how would you fix it?
Show answer
It can break antisymmetry, and as a result transitivity. With scores 2,000,000,000 and -2,000,000,000 the difference exceeds Integer.MAX_VALUE and overflows, so the sign is wrong and both argument orders can return the same sign. Fix it with Comparator.comparingInt(Score::getScore) or (a, b) -> Integer.compare(a.getScore(), b.getScore()), which never overflow. (Replace Score with the actual class name.)
Exercise
A TreeSet<Employee> is built with a comparator that compares only department. After adding 50 employees from 5 departments, the set has 5 elements. Does this break the comparator contract? What is the cause, and what would you change to keep all 50?
Show answer
It does not break the contract. The comparator is antisymmetric and transitive, and it is simply not consistent with equals. A TreeSet treats a comparison result of 0 as "same element", so it keeps one employee per department. To keep all 50, add tie-breaking keys such as .thenComparing(Employee::getId) so that only truly identical employees compare as 0.
Exercise
Why can a comparator that treats values within 0.5 of each other as equal pass a test on three elements and still throw IllegalArgumentException: Comparison method violates its general contract! in production?
Show answer
Tolerance-based equality is not transitive, so it violates the contract. TimSort only checks for inconsistency during merges of larger runs, which happen with about 32 or more elements. On small lists it never reaches that check and returns an arbitrary arrangement without complaint. The failure depends on input size and data, not on the comparator alone.