What is the difference between the Comparable and Comparator interfaces?
`Comparable` and `Comparator` are both interfaces used for ordering objects, but they serve different design purposes.
`Comparable<T>` is implemented by a class to define its natural ordering. The single method `compareTo(T other)` returns a negative integer if `this` is less than `other`, zero if equal, and a positive integer if greater. A class implementing `Comparable` is saying: "I have a well-defined, canonical sort order." Examples: `String` (lexicographic), `Integer` (numeric), `Date` (chronological). Methods like `Collections.sort(list)` and `Arrays.sort(arr)` use natural ordering by default.
`Comparator<T>` is a separate strategy object that defines an ordering independent of the class being sorted. Its method `compare(T o1, T o2)` has the same return convention. You use a `Comparator` when you need a sort order other than the natural one, when the class you are sorting doesn't implement `Comparable`, or when you need multiple orderings for the same type.
Java 8 enriched `Comparator` with default methods: `Comparator.comparing()` creates comparators from key extractors; `thenComparing()` chains comparators for multi-level sorting; `reversed()` inverts the order. This makes complex sort logic concise: `Comparator.comparing(Person::getLastName).thenComparing(Person::getFirstName)`.
The design choice: implement `Comparable` when there is one obvious, universally applicable ordering for the type. Use `Comparator` for alternative orderings or when you cannot modify the class (e.g., sorting third-party objects).
A practical note: `TreeMap` and `TreeSet` use either the natural ordering (Comparable) or a provided Comparator. If neither is available, they throw `ClassCastException` at runtime.
| Aspect | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(T o) | compare(T o1, T o2) |
| Ordering type | Natural (single, built-in) | Custom (multiple, external) |
| Modifies class? | Yes — implemented by the class | No — defined separately |
| Java 8 extras | None | comparing(), thenComparing(), reversed() |
| Use when | One canonical sort order | Alternative/multiple orderings |
Correctly contrasts natural ordering (Comparable, compareTo) with external ordering (Comparator, compare) and gives examples of each.
Also covers Java 8 Comparator factory methods, TreeMap/TreeSet behavior, and the design guidance for when to use each.
Reading the answer is step one. Explaining it unprompted — under interview pressure — is what actually matters. Get AI-graded feedback on your answer with follow-up probes on your weak points.
Get Graded — Free Assessment