Sub topic 3
The Rules a Comparison Must Follow
Assume you know Java classes, interfaces, generics, collections, equals, and basic lambda syntax. This chapter focuses on the contract that makes a comparison reliable. A comparison contract is the set of rules that every Comparable or Comparator implementation should obey.
What a comparison result means
The compareTo method and the compare method return an int:
- A negative value means the first object comes before the second.
- Zero means the objects are equivalent for this ordering.
- A positive value means the first object comes after the second.
The exact value does not matter. Only its sign matters. Returning -1, 0, or 1 is valid, but a comparison may return any negative or positive integer.
public final class Score implements Comparable<Score> {
private final int points;
public Score(int points) {
this.points = points;
}
@Override
public int compareTo(Score other) {
if (other == null) {
throw new NullPointerException("other");
}
return Integer.compare(points, other.points);
}
@Override
public String toString() {
return Integer.toString(points);
}
public static void main(String[] args) {
Score lower = new Score(10);
Score higher = new Score(20);
System.out.println(lower.compareTo(higher) < 0); // true
System.out.println(lower.compareTo(lower) == 0); // true
System.out.println(higher.compareTo(lower) > 0); // true
}
}This comparison orders scores from the smallest number of points to the largest.
The comparison laws
A comparison must behave consistently no matter where it is used. Sorting algorithms and sorted collections depend on these laws.
| Law | Required behavior | Example |
|---|---|---|
| Sign reversal | Reversing the arguments reverses the result's sign | If `compare(a, b)` is negative, `compare(b, a)` is positive |
| Transitivity | A chain of “before” results stays ordered | If `a < b` and `b < c`, then `a < c` |
| Zero consistency | If two objects compare as equal, they have the same ordering relationship with another object | If `compare(a, b) == 0`, comparisons with `c` must agree |
For Comparable, these laws apply to a.compareTo(b). For Comparator, they apply to comparator.compare(a, b).
The zero-consistency rule is especially important. If a and b compare as zero, then a third object c should not see one of them as less than c while seeing the other as greater than c.
Why subtraction is unsafe
This code looks short, but it can fail:
Comparator<Integer> unsafe = (a, b) -> a - b;Integer arithmetic can overflow. For example, subtracting -1 from Integer.MAX_VALUE produces a negative result after overflow, even though the first number is larger.
Use a comparison method instead:
Comparator<Integer> safe = Integer::compare;
System.out.println(safe.compare(Integer.MAX_VALUE, -1) > 0); // trueFor object fields, use a comparator factory such as Comparator.comparingInt when available, or compare the fields explicitly. Never assume that subtraction preserves the correct ordering.
Equality and comparison
Comparison zero does not always mean equals returns true. Java permits this, although consistency is usually easier to understand.
BigDecimal demonstrates the difference. new BigDecimal("1.0") and new BigDecimal("1.00") are unequal according to equals, but their compareTo result is zero because they represent the same numeric value. A TreeSet therefore treats them as one ordered element.
Check your comparator
When writing a comparison, test equal values, values in both argument orders, boundary values, and chains of three values. These tests expose sign errors, overflow, and non-transitive rules before they affect a collection.
Exercise
What is wrong with (a, b) -> a - b when comparing integers, and what should replace it?
Show answer
Integer subtraction can overflow and return the wrong sign. Use Integer.compare(a, b) or the method reference Integer::compare.