Lesson · Collections Framework
Comparable vs Comparator: two roads to an order
16 min readComparable & Comparator
Comparable is the order a class declares about itself; Comparator is an order supplied from outside. Sorting, trees, heaps and searches all consume one of the two, and one famous bug lives in their difference.
Sorting says no
The first time you ask Java to sort a list of your own objects, it refuses:
class Card { int rank; String suit; } // no order declared List<Card> hand = ...; Collections.sort(hand); // error: no suitable method found for sort(List<Card>) // inference variable T#1 has incompatible bounds // equality constraints: Card // upper bounds: Comparable<? super T#1>
Predict: the compiler is asking one question: what does it mean for one Card to come before another? A class answers with Comparable. A caller can answer instead, with Comparator.
Comparable: the class declares its own order
Comparable<T> has a single method, compareTo. Its return value is a direction, not a distance:
class Card implements Comparable<Card> { public int compareTo(Card other) { int byRank = Integer.compare(this.rank, other.rank); return byRank != 0 ? byRank : this.suit.compareTo(other.suit); } }
| compareTo returns | Meaning | Sort places it |
|---|---|---|
| a negative number | this object comes before the argument | earlier |
| zero | the two are equal in this ordering | same position |
| a positive number | this object comes after the argument | later |
- Natural ordering is the phrase for this declared order: String sorts alphabetically, Integer numerically, LocalDate chronologically.
- Who uses it:
Collections.sort(list),list.sort(null),TreeSetandTreeMapwithout a comparator,Collections.min/max, andPriorityQueueby default. - Write one compareTo, get every tool. Once the class declares its order, all of those accept it without further configuration.
Comparator: an order from outside
A Comparator is the same idea as an object of its own. The class stays untouched, and the caller supplies the order:
Comparator<Card> bySuit = (a, b) -> a.suit.compareTo(b.suit); hand.sort(bySuit); // this call: suit first Collections.sort(hand); // everywhere else: natural order
- One class, many orders: by rank, by suit, by suit then rank. Each is a Comparator value, not a change to the class.
- Comparator.compare(a, b) has the same sign contract as compareTo: negative, zero or positive.
- Accepted where order matters:
list.sort(comparator),new TreeSet<>(comparator),new PriorityQueue<>(comparator),Collections.binarySearch(list, key, comparator), andstream.sorted(comparator).
The division of labour: Comparable answers "what is this type's order?". Comparator answers "order it this way, just for this call". When a second order appears, the class should not grow a second compareTo.
Ordering board · four orders for one list
pick an orderThe same three words, reordered
Delegates to String's compareTo: the type's own declared order.
The comparator, as code
words.sort(Comparator.naturalOrder());
What compareTo and compare may return
Comparator.naturalOrder() delegates to the type's compareTo; every chip above is the same list, three words apart.
The fluent combinators
Composing orders is rare enough to forget the vocabulary, and common enough to need it weekly:
words.sort(Comparator.comparingInt(String::length).reversed() .thenComparing(Comparator.naturalOrder()));
Comparator.comparing(Card::suit)builds an order from any key function. UsecomparingIntfor int keys to avoid boxing..thenComparing(...)breaks ties with a second order, evaluated only when the first says zero..reversed()flips an existing order without rewriting it..nullsFirst()and.nullsLast()wrap an order so null keys do not throw.
Read a chain like a sentence: longest word first, ties broken alphabetically. Every combinator returns a new Comparator, so the pieces stay reusable.
The subtraction trap
The sign contract invites a shortcut: return a minus b. It works in every test, and then it fails on one pair of extreme values:
int big = Integer.MAX_VALUE; int small = -10; System.out.println(big - small); // -2147483639: overflowed! System.out.println(Integer.compare(big, small)); // 1: the honest answer
bigclearly comes aftersmall, so the comparison must return a positive number. The subtraction wrapped around and returned a negative one.- A comparator that lies about the sign corrupts every algorithm built on it: sorts produce scrambled results, and searches miss entries that are present.
- Use the helpers:
Integer.compare,Long.compare,Double.comparefor primitives;Comparator.comparingXfor key extraction.
Never compute a difference inside compareTo or compare. Subtract only when the values provably fit, which is another way of saying never.
Who consumes an order, and the one rule they share
Every ordering consumer stores or assumes the SAME order for the life of the data:
TreeSetandTreeMapcompare on every insert, lookup and removal. The comparator is the tree's identity.PriorityQueuecompares on every offer and poll; ties pop in unspecified order.Collections.binarySearch(list, key, comparator)must be given the comparator the list was sorted with. A different one gives silently wrong answers, not an exception.stream.sorted(comparator)sorts a copy; the source stays untouched.
One rule for all of them: do not change a comparator's answers while data depends on it. Order is a contract, and breaking it invalidates the structure, not just one result.
The ordering playbook
Choosing and writing an order, in order:
- Does the type have one obvious order? Declare it with Comparable.
- Need a second order? Write a Comparator at the call site and leave the class alone.
- Compose instead of repeating: comparing, thenComparing, reversed.
- Never write a - b. Use Integer.compare or a comparingInt combinator.
- Sort and search with the same comparator, or do not search at all.
Natural ordering is a promise; comparators are opinions. Put the promise on the type, put the opinions at the call site, and every sorted structure behaves predictably.
Comparable lives on the type; Comparator lives beside it
Implement Comparable when the type has a natural order that every caller would agree on. Reach for Comparator when the order is a choice: a different ranking, a tie-breaker, a null policy. Both speak the same language of negative, zero and positive, both are consumed by sort, trees, heaps and searches, and both must never be written as a subtraction.
Interview angles
Comparable or Comparator: how do you decide?+
Comparable when the type has one natural order that belongs to the class itself. Comparator when the order is a caller's choice, or when a second order is needed.
The test: would every consumer of this type agree on the order? Timestamps and amounts: yes, declare it. A UI that needs users sorted by name in one screen and by signup date in another: those are opinions, keep them as Comparator values near the screen.
Common misconception: That Comparator replaces Comparable, or that a class needs both. Most classes implement one or none.
Follow-up: What does TreeSet feel about the distinction?
What contract must compareTo and compare obey?+
Return a negative number when the first argument should come first, zero when they are equal in this order, positive when the first comes later. The sign is the signal, the magnitude means nothing.
The contract comes with obligations: antisymmetry (a versus b has the opposite sign of b versus a), transitivity, and consistency with equals for sorted sets and maps, otherwise equal elements can coexist and lookups miss. The one-line version: an order must be total and stable in its answers.
Common misconception: That the return value is a distance between elements. It is a direction, and callers may only read its sign.
Follow-up: What breaks in a TreeSet when the order contradicts equals?
Why is `a - b` banned inside a comparator?+
Integer subtraction overflows: Integer.MAX_VALUE - (-10) returns a negative number, so the comparator claims the larger value comes first, and every algorithm on top of it goes wrong.
The overflow pair is rare, which is the trap: tests pass, production has the one pair of extreme longs or timestamps. Use Integer.compare, Long.compare or Comparator.comparingInt, which are built for exact sign reporting.
return Integer.compare(this.rank, other.rank); // safe return this.rank - other.rank; // overflows
Common misconception: That ranges make it safe: sorting IDs from 0 to 1,000,000 passes, then one sentinel value near Integer.MAX_VALUE joins the table.
Follow-up: Where else does a comparator's sign get consumed?
You sort a list with one comparator, then binarySearch it with another. What happens?+
Nothing dramatic: you get a wrong answer. Binary search trusts the order, prunes half the list on every probe, and reports "not found" for entries that are present.
Sort and search must share the same order, including its tie-breakers and its null policy. The same applies to TreeSet and TreeMap: the comparator given to the constructor becomes the collection's identity, so a lookup with an "equal" but differently ordered key can still land in the right place, while a mismatched order cannot find anything reliably.
Common misconception: That binarySearch throws on a wrong order. It does not detect the problem; it just returns wrong results faster.
Follow-up: And if the comparator is inconsistent with equals?
When do you reach for the fluent combinators?+
As soon as an order needs a tie-breaker or a key extraction: Comparator.comparing(Card::getSuit).thenComparingInt(Card::getRank) reads exactly like the rule.
comparing and comparingInt build an order from a key; thenComparing chains; reversed flips; nullsFirst and nullsLast make null policy explicit. Each returns a new Comparator, so composed orders stay reusable and testable in isolation.
Common misconception: That combinators are syntax sugar for a small win: compared to a hand-written compare, they remove the entire class of sign and overflow mistakes.
Follow-up: How would you build "longest first, ties alphabetical"?