Sub topic 13
Choosing between Comparable and Comparator
This chapter assumes you know Java classes, interfaces and generics, lambdas and method references, the List and TreeSet basics, and how equals and hashCode work. It also assumes you have read the earlier chapters on compareTo, compare, the comparison contract and the Comparator factory methods. Here you learn to decide which tool fits a design, and what each choice costs you later.
The decision in one sentence
Use Comparable when a type has one obvious, unsurprising order that every user of the type would expect. Use Comparator for every other order, and for any type you cannot or should not modify.
The two are not rivals. Comparable is the default order stored inside the class. A Comparator is an order supplied from outside for one particular use. Many well-designed types provide both.
What each choice means
| Question | Comparable | Comparator |
|---|---|---|
| Where does the order live? | Inside the class, in `compareTo` | In a separate object, lambda or constant |
| How many orders per type? | Exactly one | As many as you like |
| Who must be able to edit the class? | You | Nobody |
| What uses it automatically? | `Collections.sort(list)`, `Arrays.sort(array)`, `TreeSet`, `TreeMap`, `PriorityQueue` with no comparator argument | Only the call you pass it to |
| What happens if the order is missing? | Those calls throw `ClassCastException` at run time | The call does not compile or you pass nothing |
| Can it be changed per call site? | No | Yes |
The "automatically used" row matters most. If your class implements Comparable, someone can drop it into a TreeSet without a second thought. The TreeSet then treats compareTo as the definition of equality. Implementing Comparable is therefore a public promise about the whole type, not a convenience.
A decision flow
When Comparable is the right choice
Choose Comparable when all of these hold:
- The order is the one a reader would guess. Numbers, dates, strings and version numbers all fit. A
Versionsorts by major, then minor. - The order is stable over time. Changing it later changes the behavior of every
TreeSet,TreeMapand sorted list in code you do not control. - The order is consistent with
equals, or you are willing to document that it is not. - You own the class.
An order is a poor candidate for Comparable when you have to argue for it. The chapter's earlier Person example orders by age. That is fine for teaching the interface, but in a real system "natural" order for a person is unclear. It could be age, surname, or an ID. When two reasonable developers would disagree, do not pick a winner inside the class. Use named comparators instead, so each call site says what it means.
Enums are a good reference point. They are Comparable by declaration order, and that order is a deliberate part of the type's design.
When Comparator is the right choice
Choose Comparator when any of these apply:
- You cannot edit the type. Library classes, generated classes and types from other teams need an external order.
- You need several orders. Employees sort by name in one report, by salary in another and by department then salary in a third.
- The order depends on context, such as a locale-aware
Collatoror a user's chosen column in a table. - You want to avoid committing the class to a public promise. A comparator kept private in one class cannot leak into someone else's
TreeSet.
Comparators also compose. thenComparing, reversed and nullsFirst build new orders out of small ones without touching the element class.
Using both: a worked example
The following program is complete. Version has a clear natural order, so it implements Comparable. Employee has no single obvious order, so it exposes named comparators instead.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.PriorityQueue;
import java.util.TreeSet;
public class ChoosingDemo {
static final class Version implements Comparable<Version> {
private static final Comparator<Version> ORDER =
Comparator.comparingInt((Version v) -> v.major)
.thenComparingInt(v -> v.minor);
private final int major;
private final int minor;
Version(int major, int minor) {
this.major = major;
this.minor = minor;
}
@Override
public int compareTo(Version other) {
return ORDER.compare(this, other);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Version)) return false;
Version v = (Version) o;
return major == v.major && minor == v.minor;
}
@Override
public int hashCode() {
return Objects.hash(major, minor);
}
@Override
public String toString() {
return "v" + major + "." + minor;
}
}
static final class Employee {
static final Comparator<Employee> BY_NAME =
Comparator.comparing(Employee::getName);
static final Comparator<Employee> BY_SALARY_DESC =
Comparator.comparingInt(Employee::getSalary).reversed();
static final Comparator<Employee> BY_DEPARTMENT_THEN_SALARY_DESC =
Comparator.comparing(Employee::getDepartment)
.thenComparing(BY_SALARY_DESC);
private final String name;
private final String department;
private final int salary;
Employee(String name, String department, int salary) {
this.name = name;
this.department = department;
this.salary = salary;
}
String getName() { return name; }
String getDepartment() { return department; }
int getSalary() { return salary; }
@Override
public String toString() { return name; }
}
public static void main(String[] args) {
List<Version> versions = new ArrayList<>(Arrays.asList(
new Version(2, 0), new Version(1, 10), new Version(1, 2)));
versions.sort(null); // null means natural ordering
System.out.println(versions); // [v1.2, v1.10, v2.0]
TreeSet<Version> released = new TreeSet<>(versions);
System.out.println(released.last()); // v2.0
List<Employee> staff = new ArrayList<>(Arrays.asList(
new Employee("Ana", "eng", 120),
new Employee("Bo", "eng", 150),
new Employee("Cy", "ops", 90),
new Employee("Di", "ops", 110)));
staff.sort(Employee.BY_NAME);
System.out.println(staff); // [Ana, Bo, Cy, Di]
staff.sort(Employee.BY_DEPARTMENT_THEN_SALARY_DESC);
System.out.println(staff); // [Bo, Ana, Di, Cy]
PriorityQueue<Employee> payroll =
new PriorityQueue<>(Employee.BY_SALARY_DESC);
payroll.addAll(staff);
System.out.println(payroll.poll()); // Bo
}
}Three design choices are worth noticing.
Version.compareTodelegates to a private comparator constant. This keeps the logic in one place and uses the factory methods rather than hand-writtenifchains.VersionoverridesequalsandhashCodeso they agree withcompareTo. Two versions compare as 0 exactly when they are equal.Employeehas nocompareTo. PassingEmployeeto a no-argumentTreeSetconstructor would fail, which is the correct outcome for a type with no agreed order.
Note that versions.sort(null) is legal and means "use natural ordering". Collections.sort(versions) says the same thing more readably.
Edge cases and costs
Exposing comparators as constants
Public static Comparator constants, like Employee.BY_NAME, give callers named orders without making the class Comparable. The JDK does this with String.CASE_INSENSITIVE_ORDER. Name each constant for what it sorts by, and include the direction when it is not ascending.
You cannot add Comparable to a type you do not own
If you wrap or subclass a library type only to add compareTo, you may break its equals contract. A comparator avoids that problem.
Changing a natural order is a breaking change
A natural order is observable in every TreeSet iteration and every default sort. Changing it later is a behavior change even when the signature stays the same. A comparator constant can be replaced or added to with far less risk.
Inheritance weakens Comparable
If Base implements Comparable<Base> and a subclass adds a field that should affect the order, you cannot keep the contract's symmetry across types. sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) cannot hold when x is a Base and y is a subclass that compares more fields. The usual fix is composition and a comparator, or making the class final.
Consistency with equals is a design input
If your natural order ignores some fields that equals uses, TreeSet will silently drop elements that HashSet would keep. The BigDecimal example from the earlier chapter showed this with 1.0 and 1.00. The same choice applies to Comparator: a TreeSet built from a name-only comparator holds one employee per name. That is sometimes what you want, but check it deliberately.
Quick reference for common cases
| Situation | Recommended approach |
|---|---|
| Value type with one canonical order (version, money, date range) | `Comparable`, consistent with `equals` |
| Domain entity with several plausible orders | No `Comparable`; named `Comparator` constants |
| Library or third-party class | `Comparator` |
| One-off sort in a single method | Inline comparator with `Comparator.comparing` |
| Order that depends on user input or locale | `Comparator` created at run time |
| Sorted collection that should reject unorderable elements | `Comparable` element type, so `TreeSet` works without arguments |
Common mistakes in this decision
- Implementing
Comparableon an entity with a mutable ID or mutable fields, then storing it in aTreeSet. If the sort key changes after insertion, the set can no longer find the element. - Writing one
Comparablethat is correct for one report and wrong for the next, then adding flags tocompareToto switch modes. Use separate comparators instead. - Forgetting that
PriorityQueueandTreeMapalso use natural order when given no comparator, and getting aClassCastExceptionwhen the element type is notComparable. - Making
compareToinconsistent withequalswithout documenting it. The Javadoc ofComparablerecommends noting the exception.
Exercise
A Ticket class has the fields id, priority, createdAt and assignee. Support staff sort tickets by priority in one view, by creation time in another, and by assignee in a third. Should Ticket implement Comparable<Ticket>? What would you provide instead?
Show answer
No. Three plausible orders exist, and none is the one every user would expect, so a single compareTo would favor one view over the others and become a permanent public promise. Provide named comparator constants such as BY_PRIORITY_DESC, BY_CREATED_AT and BY_ASSIGNEE_THEN_ID on Ticket, built with Comparator.comparing and thenComparing. Each view then states its order at the call site.
Exercise
You write class Money implements Comparable<Money> ordering only by amount, while equals compares amount and currency. You then add new Money(5, "USD") and new Money(5, "EUR") to a TreeSet. How many elements does the set hold, and how would you fix the design?
Show answer
The set holds one element, because compareTo returns 0 for the two values and TreeSet treats that as a duplicate. The order is inconsistent with equals. Fix it by making compareTo also compare currency as a tie-breaker, for example Comparator.comparing(Money::getCurrency).thenComparing(Money::getAmount), so it returns 0 only when equals is true. If a cross-currency amount order is still needed, keep it as a separate Comparator.