Sub topic 12
Pitfalls: subtraction overflow, inconsistent comparisons and mutable keys
This chapter assumes that you understand Java classes, interfaces, generics, lambdas, collections, and the equals and hashCode methods. The comparison rules matter because Java uses them not only to sort values, but also to place values inside sorted collections.
Do not compare by subtraction
A common shortcut is to compare integers by subtracting them:
Comparator<Integer> broken = (a, b) -> a - b;This fails when the subtraction overflows the range of int. Java silently wraps the result. The sign can become incorrect, so a larger value may appear to be smaller.
import java.util.Comparator;
public class OrderingPitfalls {
public static void main(String[] args) {
Comparator<Integer> broken = (a, b) -> a - b;
Comparator<Integer> correct = Integer::compare;
System.out.println(broken.compare(Integer.MAX_VALUE, -1));
System.out.println(correct.compare(Integer.MAX_VALUE, -1));
}
}The broken comparator returns a negative value even though Integer.MAX_VALUE is greater than -1. Use Integer.compare, Long.compare, or a factory such as Comparator.comparingInt.
Keep comparisons consistent
A comparator must provide a stable ordering. If compare(a, b) says that a comes before b, reversing the arguments should say that b comes after a. The comparison should also be transitive: if a comes before b, and b comes before c, then a should come before c.
A comparator that changes its answer or violates transitivity can make sorting unpredictable. It can also corrupt the logical behavior of TreeSet, TreeMap, and PriorityQueue.
| Problem | Result | Better approach |
|---|---|---|
| Subtraction overflow | Wrong ordering | Use `Integer.compare` |
| Different comparison rules at different times | Unstable sorting | Compare fixed properties |
| Non-transitive rules | Unpredictable collections | Define one consistent order |
| Returning zero for unrelated values | Values may be treated as duplicates | Choose keys carefully |
A comparator can also disagree with equals. For example, a comparator that compares people only by age returns zero for two different people of the same age. A TreeSet then treats those people as duplicates, even if equals says they are different.
Do not mutate sorted keys
Sorted collections locate elements using their ordering. If a field used by the comparator changes after insertion, the element remains in its old position. The collection does not automatically rebuild itself.
import java.util.Comparator;
import java.util.TreeSet;
public class MutableKeyExample {
static class Person {
private final String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
void setAge(int age) {
this.age = age;
}
int getAge() {
return age;
}
@Override
public String toString() {
return name + " (" + age + ")";
}
}
public static void main(String[] args) {
TreeSet<Person> people =
new TreeSet<>(Comparator.comparingInt(Person::getAge));
Person ana = new Person("Ana", 20);
Person bo = new Person("Bo", 30);
people.add(ana);
people.add(bo);
ana.setAge(40);
System.out.println(people);
}
}The collection can print [Ana (40), Bo (30)], even though that order is no longer ascending by age. Searches and removals can also give surprising results because the tree still reflects the old age.
Use immutable fields for ordering keys whenever possible. If a key must change, remove the object, change it, and add it again:
people.remove(ana);
ana.setAge(40);
people.add(ana);This works only when the collection can find the object using its current state. Designing immutable key objects is safer.
Never use a comparator based on mutable state in a sorted collection unless you remove and reinsert the object after every key change.A practical review checklist
Before using a Comparable or Comparator, ask:
- Can the comparison overflow?
- Is the result consistent, transitive, and deterministic?
- Can two unequal objects compare as zero?
- Can any ordering field change while the object is stored?
- Does the ordering match the collection's intended meaning of a duplicate?
Exercise
What is wrong with (a, b) -> a - b, and how should it be replaced?
Show answer
Subtraction can overflow and produce the wrong sign. Replace it with Integer.compare(a, b) or use Comparator.comparingInt(...).