What are the key differences between Comparable and Comparator in Java
Last updated: September 2026 — rewritten with code examples, a comparison table, and interview Q&A.
Comparable vs Comparator is a staple interview question for 2–5 year experienced candidates. The interviewer wants to hear two things: where the comparison logic lives, and how many orderings each one allows.
Comparable vs Comparator: the differences
| Feature | Comparable | Comparator |
|---|---|---|
| Package | java.lang | java.util |
| Method | compareTo(Object o) — compares this with another | compare(Object o1, Object o2) — compares two objects |
| Where it lives | Inside the class being sorted | Any separate class |
| Number of orderings | One — the "natural" ordering | Unlimited — one per Comparator |
| Sorting type | Natural (numeric, alphabetical, chronological) | Custom (by age, by date, by any field) |
| Can sort third-party classes? | No — you can't modify their source | Yes — the logic lives outside |
In code: Comparable (natural ordering)
public class Contact implements Comparable<Contact> {
private String emailId;
@Override
public int compareTo(Contact o) {
return this.emailId.compareTo(o.getEmailId()); // natural: by email
}
}
Collections.sort(contacts); // uses compareTo
In code: Comparator (custom ordering)
// sort orders by date, newest first — without touching the Order class
Comparator<Order> byDateDesc = (o1, o2) ->
o2.getOrderDate().compareTo(o1.getOrderDate());
Collections.sort(orders, byDateDesc);
// need another ordering? just write another Comparator
Comparator<Order> byEmail = Comparator.comparing(Order::getEmailId);
Collections.sort(orders, byEmail);
Interview rapid-fire
- When would you pick Comparator over Comparable? — Multiple orderings needed, or the class source isn't yours to modify.
- What does
compareToreturn? — Negative if this < other, zero if equal, positive if this > other. - Can a class implement both? — Yes. Comparable defines the default; Comparators override per use-case.
- Java 8+ shortcut for Comparators? —
Comparator.comparing(Order::getEmailId)plus.thenComparing(...)chains. - What if compareTo is inconsistent with equals? — Sorted collections (
TreeSet) may behave strangely — e.g., "duplicate" elimination thatequalsdisagrees with.
Related reading
- Java program using the Comparable interface
- Java program using the Comparator interface
- Why String is immutable — another evergreen classic
Comments
Post a Comment