Lesson · The Object Class & Core Contracts
Ordering contracts: compareTo and its quiet conspiracies
16 min readOrdering Contracts
compareTo returns a sign, obeys arithmetic-like laws, and is trusted by TreeSet and TreeMap as the final word on sameness. When it disagrees with equals, collections disagree with each other.
Two names walked into a TreeSet
A case-insensitive set receives two strings that look different and keeps one:
Set<String> names = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); names.add("ada"); names.add("ADA"); // a second element... or not? System.out.println(names.size()); // predict before reading on
Predict: size 1. The comparator returns 0 for the two spellings, and sorted collections treat compareTo == 0 as 'the same element', no matter what equals thinks. The add returned false in spirit: the second name was quietly folded into the first. That sentence is the entire lesson.
The compareTo contract
compareTo returns an int with exactly three meanings: negative (this sorts first), zero (the same place), positive (this sorts second). The promises around that sign:
| Promise | Means | Broken by |
|---|---|---|
| Sign antisymmetry | sgn(a.compareTo(b)) == -sgn(b.compareTo(a)) | Comparators that let both directions say 'greater' |
| Transitivity | If a < b and b < c then a < c | Chained tie-breakers that contradict each other |
| Consistency with equals | a.compareTo(b) == 0 exactly when a.equals(b) (strongly recommended) | BigDecimal: 1.0 and 1.00 compare equal yet are not equals |
| Reflexivity | x.compareTo(x) is 0 | Comparisons against changing state |
The consistency line is where collections split. A HashSet asks equals; a TreeSet asks compareTo; when the two answers differ, the same two objects are one element in one collection and two in the other, with no error anywhere.
Writing compareTo and Comparators
The field-by-field recipe, and its modern alternative:
class Employee implements Comparable<Employee> { @Override public int compareTo(Employee other) { int byName = name.compareTo(other.name); return byName != 0 ? byName : Integer.compare(age, other.age); } } // an external order, composed from extractors: Comparator<Employee> byAge = Comparator.comparingInt((Employee e) -> e.age) .thenComparing(e -> e.name);
- Compare one field at a time; return the first non-zero answer, or continue to the next field.
- Use the type's own compareTo for reference fields (
Stringships a good one) andInteger.compare/Double.comparefor primitives (never subtraction: overflow lies). - Implement
Comparableonly when a class has one obvious natural order; everything else belongs in externalComparators, which can be many and named. - Comparator chains (
comparing,thenComparing) compose orderings safely;reversed()andnullsFirst()cover the standard variations.
Never return subtraction. a.score - b.score overflows to the wrong sign for distant ints and reads as correct for years; Integer.compare exists exactly for this.
Ordering court · equals versus compareTo
pick a caseThe case
A class implements compareTo field by field and equals/hashCode on the same fields; two equal-by-value instances are added.
asks equals
HashSet: 1 element
asks compareTo
TreeSet: 1 element
Agreement
compareTo == 0 exactly when equals is true: the two collections agree, and everything downstream may too.
All element counts were produced by running the code with javac and java against real JDK collections.
What silently breaks when the contract bends
Every violation produces the same class of symptom: collections proceed with confident wrong answers.
- Silent deduplication:
TreeSetfoldscompareTo == 0elements together, even whenequalssays different; the verified BigDecimal case keeps one element whereHashSetkeeps two. - Cross-collection disagreement: the same two objects are one element in a
TreeMapand two in aHashMap; tests written against one flake against the other. - `get` that misses what `put` stored: a
TreeMapfinds keys by comparison, so a comparator inconsistent with the key's stored position loses lookups exactly like mismatched hashes do forHashMap. - The loud case, for contrast: a comparator so inconsistent that sorting breaks its own logic eventually throws
IllegalArgumentException: Comparison method violates its general contract!from TimSort; prefer this failure to the silent ones, and still fix the comparator.
A comparator is a claim about an order existing. Transitivity, antisymmetry and a stable zero are what 'sorted' means; bend them and the tree is quietly walking a path that does not match its own rules.
The ordering playbook
Choosing and shipping an order, in order:
- Ask whether the class has one natural order. Value-like classes (money, dates, IDs) usually do; service objects do not.
- Write
compareTofield by field; use the field types' own comparisons and never plain subtraction. - Keep it consistent with
equals: return 0 for exactly the objects equals calls equal; where impossible (BigDecimal's scale), document it and avoid mixing such keys into sorted collections. - Prefer named
Comparators for every other order; compose chains instead of overloading one comparator with modes. - Test with the pair that lies closest: two objects that are 'the same' by one definition and not the other; the container sizes expose the disagreement instantly.
A sort is a promise about the whole set, and containers trust it absolutely. Keep compareTo's zero aligned with equals, and TreeSet, TreeMap and sort all behave; misalign them and nothing throws, which is worse.
compareTo's zero is the sorted world's equals
The sign convention, antisymmetry and transitivity make ordering work; consistency with equals makes it agree with the rest of the language. TreeSet and TreeMap treat compareTo == 0 as sameness, silently deduplicating and losing lookups when the two definitions of 'same' diverge.
Interview angles
What are compareTo's promises?+
A sign with three meanings, antisymmetry (opposite calls give opposite signs), transitivity (order chains hold), reflexivity (self compares 0), and strong recommendation of consistency: zero exactly when equals is true.
The shape mirrors equals' contract because ordering and sameness are the same question asked with a richer answer: where, not just whether. The optional zero-vs-nonzero alignment is Comparable's consistency clause.
x.compareTo(x); // 0, always a.compareTo(b); // negative of b.compareTo(a) in sign a < b, b < c // then a < c
Common misconception: That any formula producing some order is fine. Sorting algorithms assume the laws; broken ones either mis-sort or throw from deep inside TimSort.
Follow-up: Which law does a non-transitive chained comparator break first?
Why should compareTo agree with equals?+
Because sorted collections translate compareTo == 0 into 'same element': TreeSet deduplicates and TreeMap treats it as one key, while hash collections ask equals instead.
When the two disagree, the same collection contents mean different things depending on the structure: verified BigDecimal("1.0") and BigDecimal("1.00") are two elements in a HashSet and one in a TreeSet. The language allows the disagreement; collections merely reflect it.
new BigDecimal("1.0").equals(new BigDecimal("1.00")); // false: scale differs new BigDecimal("1.0").compareTo(new BigDecimal("1.00")); // 0: value equal // HashSet: 2 elements; TreeSet: 1 element
Common misconception: That BigDecimal is buggy. Its equals is deliberately exact (scale matters for money) and its compareTo deliberately numerical; the tension is documented, and callers choose the container accordingly.
Follow-up: Where else does the JDK live with this tension deliberately?
What breaks in a TreeMap when ordering misbehaves?+
Lookups miss the way hash mismatches do: the tree walks by comparison, so a key that will not compare as zero is never found, even though it sits in the map.
The silent failures (deduplication, missed lookups, cross-collection disagreement) all stem from the tree trusting the comparator with its structure. Fixable only at the comparator or the compareTo, never by the caller.
map.put("ada", 1); map.put("ADA", 2); // case-insensitive order: same key, value overwritten map.size(); // 1
Common misconception: That the map should fall back to equals when comparison is doubtful. The structure was built by comparison; equals never enters the picture.
Follow-up: Which fix restores agreement without changing either definition?
Comparable or Comparator: when each?+
Comparable is the class's single natural order, implemented by the class itself; Comparator is any number of external, named orders provided by callers.
Collections.sort, TreeSet and TreeMap use the natural order when none is given, and a Comparator when one is. Composition helpers (comparing, thenComparing, reversed, nullsFirst) let orderings be built, not typed.
list.sort(Comparator.comparing((Employee e) -> e.name) .thenComparingInt(e -> e.age));
Common misconception: That implementing Comparable prohibits other orders. It provides the default; comparators add as many named orders as callers need on top.
Follow-up: What happens when a class implements two natural orders conceptually?
What does 'Comparison method violates its general contract!' mean?+
Sorting detected an inconsistent comparator (usually broken transitivity) and refused: TimSort throws IllegalArgumentException instead of mis-sorting silently.
It is the loud cousin of the quiet failures: the comparator answered a<b, b<c and c<a across triples. Common causes: subtraction overflow, ties broken by different fields per comparison, or mutating state consulted mid-sort.
// a comparator whose ties drift can end in: // java.lang.IllegalArgumentException: Comparison method violates its general contract!
Common misconception: That the exception is a JDK bug. It is the JDK refusing to trust a contract that was already broken; the fix is in the comparator's logic.
Follow-up: Why can such a comparator sort small lists fine for years?