Sub topic 13
Choosing between Comparable and Comparator
This chapter assumes you know Java classes, interfaces, generics, collections, equals and hashCode, lambda expressions, and method references. The goal is to choose the right place to define an ordering.
The central choice
Comparable<T> is an interface that a class implements when the class has one clear, default ordering. That ordering is called the natural ordering. A class supplies it through compareTo.
Comparator<T> is an object that defines an ordering separately from the class being ordered. You can create several comparators for the same type.
For example, a Person class might naturally sort by an ID. A screen could instead sort people by name, age, or last login time. These screen-specific choices belong in comparators.
| Use `Comparable` when | Use `Comparator` when |
|---|---|
| One ordering is the obvious default | Several orderings are useful |
| The ordering describes the type itself | The ordering belongs to a report, screen, or operation |
| You control the class source | You need to order a class you cannot change |
| The ordering will remain stable | The rule may change independently |
A practical design example
Suppose products have a permanent product code and a display name:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class Product implements Comparable<Product> {
private final String code;
private final String name;
private final double price;
public Product(String code, String name, double price) {
this.code = code;
this.name = name;
this.price = price;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
@Override
public int compareTo(Product other) {
return code.compareTo(other.code);
}
@Override
public String toString() {
return code + ": " + name + " ($" + price + ")";
}
public static void main(String[] args) {
List<Product> products = new ArrayList<Product>();
products.add(new Product("B2", "Keyboard", 40.00));
products.add(new Product("A1", "Monitor", 180.00));
products.add(new Product("C3", "Mouse", 20.00));
products.sort(null); // Uses Product.compareTo
System.out.println(products);
Comparator<Product> byPrice =
Comparator.comparingDouble(Product::getPrice);
products.sort(byPrice);
System.out.println(products);
}
}The product code is a reasonable natural ordering because it identifies the product and does not depend on a particular user interface. Price is a separate ordering because different consumers might want ascending price, descending price, or price followed by name.
A class should not implement Comparable merely because one caller needs to sort it. That would make a local requirement part of the class's public design.
Protect the comparison contract
Whichever approach you use, the comparison must be consistent. If a.compareTo(b) or comparator.compare(a, b) returns a negative value, a comes before b. A positive value means it comes after b. Zero means the ordering considers the values tied.
The comparison should be:
- Reflexive: comparing a value with itself returns zero.
- Antisymmetric: reversing the arguments reverses the result's sign.
- Transitive: if
acomes beforebandbbeforec,acomes beforec.
Use Integer.compare, Long.compare, or comparator factory methods. Do not compare numbers by subtraction because overflow can reverse the result.
Sorted collections affect the decision
TreeSet, TreeMap, and PriorityQueue use a comparator or the natural ordering. They use a comparison result of zero to decide that two values occupy the same ordering position.
That can differ from equals. For example, a comparator that compares people only by age treats two people of the same age as tied. A TreeSet may then retain only one of them.
A concise rule
Implement Comparable for a stable, intrinsic default. Use Comparator for alternatives, external classes, context-specific rules, nullable values, or rules that may change. Test both the ordering and its interaction with equals before using it in a sorted collection.
Exercise
A Customer can be ordered by account number, name, registration date, or current balance. Should Customer implement Comparable<Customer>?
Show answer
Usually no. These are several valid business orderings, so define named Comparator<Customer> instances. Implement Comparable only if one ordering is clearly the stable natural ordering.