Sub topic 12
Pitfalls: subtraction overflow, inconsistent comparisons and mutable keys
This chapter assumes you can write a Comparable class and a Comparator, and that you know the compare contract: the sign of the result, symmetry, transitivity, and consistency with equals. The bugs below all break that contract or the assumptions behind it. They are hard to find because the code usually compiles, runs, and works on small test data.
Pitfall 1: comparing by subtraction
The most common shortcut is (a, b) -> a - b. It looks like it should return a negative number, zero, or a positive number, and for small values it does. For large values, int arithmetic wraps around and the sign flips.
import java.util.Comparator;
public class OverflowDemo {
public static void main(String[] args) {
Comparator<Integer> broken = (a, b) -> a - b;
Comparator<Integer> correct = Integer::compare;
// MAX_VALUE - (-1) is 2147483648, which does not fit in an int
System.out.println(broken.compare(Integer.MAX_VALUE, -1)); // -2147483648
System.out.println(correct.compare(Integer.MAX_VALUE, -1)); // 1
}
}The broken comparator says Integer.MAX_VALUE is smaller than -1. A sort using it can produce a wrong order, and it can also break transitivity, which leads to the next pitfall.
The same trap exists in these forms:
a.getAge() - b.getAge()is unsafe when the values can be far apart, for example timestamps or IDs.- Subtracting
longvalues and casting tointtruncates the result, so a nonzero difference can become0. - Subtracting
doublevalues and casting tointthrows away the fraction (see below).
Use Integer.compare, Long.compare, Double.compare, or Comparator.comparingInt and its relatives. These never subtract.
Comparator<Person> byAge = Comparator.comparingInt(Person::getAge);Pitfall 2: comparisons that break the contract
A sort algorithm relies on the contract. If your comparator says a == b and b == c but a < c, the algorithm has no consistent order to produce. The result depends on the algorithm and on the input order.
The usual cause is a "close enough" comparison on floating-point numbers:
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
public class SloppyDemo {
public static void main(String[] args) {
Comparator<Double> sloppy = (a, b) -> (int) (a - b); // truncates fractions
TreeSet<Double> first = new TreeSet<>(sloppy);
first.addAll(List.of(0.0, 0.6, 1.2));
System.out.println(first.size()); // 2
TreeSet<Double> second = new TreeSet<>(sloppy);
second.addAll(List.of(0.6, 0.0, 1.2));
System.out.println(second.size()); // 1
}
}Here 0.0 equals 0.6 and 0.6 equals 1.2, because the truncated differences are 0. But 0.0 is less than 1.2, because the difference of -1.2 truncates to -1. Transitivity of equality fails. The same three values give a set of size 2 or size 1 depending only on insertion order.
What the sort does when the contract is broken
List.sort and Arrays.sort on objects use TimSort. It may throw IllegalArgumentException: Comparison method violates its general contract! when it notices an inconsistency while merging runs. Do not rely on this exception, for three reasons:
- It appears only on some inputs. Short lists (fewer than 32 elements) are sorted with binary insertion sort and never throw it.
- It may not appear at all even when the comparator is wrong. You then get a silently incorrect order.
- A passing test on small data proves nothing.
A comparator that returns random results, or that depends on state that changes during the sort, breaks the contract in the same way.
Other contract violations to look for
- Returning only
1or-1. A comparator like(a, b) -> a.x < b.x ? -1 : 1never returns0for equal elements. Thencompare(a, b)andcompare(b, a)both return1, which violates the rule thatsign(compare(a, b)) == -sign(compare(b, a)). - Ignoring part of the ordering. If you compare by
lastNameand forgetfirstName, distinct people compare as equal. A sort tolerates this, because it is stable. ATreeSetorTreeMaptreats them as duplicates and drops them. - Special floating-point values.
Double.comparetreatsNaNas greater than every other value and places-0.0before0.0. Using<and>on primitives gives different answers for these values. PreferDouble.compare. - Unhandled
null. A comparator that calls a method on anullfield throwsNullPointerException. Wrap it withnullsFirstornullsLastas shown earlier.
Consistency with equals, revisited
A comparator can follow the contract and still disagree with equals. BigDecimal is the standard example: compareTo returns 0 for 1.0 and 1.00, but equals returns false. Sorted collections follow the comparator and hash collections follow equals, so the two kinds of set can disagree about the same data. If your compareTo is not consistent with equals, document it, as the JDK does.
Pitfall 3: mutating an element that is used as a key
A sorted collection places an element when you insert it, using the comparison result at that moment. It does not recheck the position later. If a field used by the comparator changes while the element is in the collection, the collection's structure no longer matches the ordering.
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.TreeSet;
public class MutableKeyDemo {
static class Task implements Comparable<Task> {
final String name;
int priority; // mutable, and used by compareTo
Task(String name, int priority) {
this.name = name;
this.priority = priority;
}
@Override
public int compareTo(Task other) {
int byPriority = Integer.compare(priority, other.priority);
return byPriority != 0 ? byPriority : name.compareTo(other.name);
}
@Override
public String toString() {
return name + "(" + priority + ")";
}
}
public static void main(String[] args) {
Task a = new Task("a", 5);
Task b = new Task("b", 3);
Task c = new Task("c", 8);
TreeSet<Task> set = new TreeSet<>();
set.add(a);
set.add(b);
set.add(c);
System.out.println(set); // [b(3), a(5), c(8)]
b.priority = 9; // mutate while stored
System.out.println(set); // [b(9), a(5), c(8)] iteration order is stale
System.out.println(set.contains(b)); // false
System.out.println(set.remove(b)); // false
System.out.println(set.size()); // 3
PriorityQueue<Task> queue = new PriorityQueue<>(Comparator.naturalOrder());
Task x = new Task("x", 5);
Task y = new Task("y", 3);
Task z = new Task("z", 8);
queue.add(x);
queue.add(y);
queue.add(z);
z.priority = 1; // z should now be first
System.out.println(queue.poll()); // y(3), not z(1)
}
}After b.priority = 9, the tree still holds b as the left child of a. contains(b) compares b(9) with the root a(5), goes right, compares with c(8), goes right again, and finds nothing. The element is still in the set, but you can no longer find it or remove it. The PriorityQueue has the same problem. Its heap was arranged when the elements were added, and poll() returns whatever is at the head without re-sorting.
Hash-based collections fail in the same way when a field used by hashCode changes.
Fixes
- Make the fields used in the comparison
final. This is the best option, because the bug becomes impossible. - If a field must change, remove the element first, change it, then add it back:
set.remove(b);
b.priority = 9;
set.add(b);- Remove the element before the change, not after. Once the field has changed, the removal fails as shown above.
- If an element can change often, keep it in a
Listand sort it when you need the order, rather than in a structure that maintains order for you.
A symptom-to-cause map
| Pitfall | Symptom | Fix |
|---|---|---|
| `a - b` comparison | Wrong sign for values far apart | `Integer.compare`, `Long.compare`, `comparingInt` |
| Truncating a `double` difference | Equal results for different values, order-dependent sets | `Double.compare` |
| Missing tie-breaker | `TreeSet` or `TreeMap` drops distinct elements | `thenComparing` on more fields |
| Returning only `1` or `-1` | Asymmetric results, possible contract exception | Return `0` for equal elements |
| Mutable key | `contains` and `remove` fail, stale order | `final` fields, or remove, change, re-add |
| Not consistent with `equals` | Hash and tree sets disagree | Document it, or align the two |
A quick contract check
When you suspect a comparator, test the three rules on a small sample that includes extreme values such as Integer.MIN_VALUE, Integer.MAX_VALUE, 0, NaN, and duplicates. Check that:
Integer.signum(c.compare(a, b)) == -Integer.signum(c.compare(b, a))for every pair.- If
compare(a, b) > 0andcompare(b, c) > 0, thencompare(a, c) > 0. - If
compare(a, b) == 0, thencompare(a, c)andcompare(b, c)have the same sign for everyc.
Exercise
A teammate writes Comparator<Long> byTime = (a, b) -> (int) (a - b); to sort timestamps in milliseconds. Name two ways this can fail and give a correct replacement.
Show answer
The difference of two long values can be larger than an int can hold. After the cast, the low 32 bits are kept, so the sign can flip or a nonzero difference can become 0. For example, a difference of 4294967296 casts to 0, so two different timestamps compare as equal. The result can also be intransitive, which breaks the contract. A correct replacement is Long::compare, or Comparator.comparingLong(...) when comparing a long field of an object.
Exercise
You store Task objects in a TreeSet ordered by priority. After you call task.setPriority(1), set.remove(task) returns false even though the task is in the set. Why does this happen, and how do you change a priority safely?
Show answer
The tree placed the task using its old priority. After the change, remove searches the tree using the new priority, follows a different path, and never reaches the node. To change the priority safely, call set.remove(task) before the change, update the priority, then call set.add(task). Alternatively, make the priority final and create a new Task object when the priority changes.