Comparable vs Comparator in Java
Comparable vs Comparator in Java: compareTo() natural ordering vs external compare() sorting. Learn when to use each with code, chaining, and interview tips.
Expected Interview Answer
Comparable defines a type's single natural ordering through the compareTo() method implemented inside the class itself, while Comparator is a separate object defining alternative orderings through compare(), letting you sort the same type many different ways without touching its code.
A class implements Comparable to say how its instances compare by default, so Collections.sort() and TreeSet work with no extra arguments. Comparator lives outside the class, so you can pass different comparators to sort by name, then by age, then in reverse, and you can build them fluently with Comparator.comparing(), thenComparing(), and reversed().
- Comparable gives a type one clear default ordering
- Comparator supplies unlimited alternative orderings
- Comparator works on classes you cannot modify
- Fluent builders like comparing() and thenComparing() are readable
- Both integrate directly with sort(), TreeSet, and TreeMap
AI Mentor Explanation
Comparable is a batting order fixed by the team itself — every player knows their default slot. Comparator is a selector's separate sheet reordering players for a specific pitch: by strike rate today, by experience tomorrow, without ever changing each player's built-in position.
Step-by-Step Explanation
Step 1
Choose the natural order
Have the class implement Comparable<T> and define compareTo(T other) returning negative, zero, or positive for less, equal, or greater.
Step 2
Enable default sorting
With compareTo() in place, Collections.sort(list) and TreeSet<T> order elements automatically with no extra argument.
Step 3
Add alternative orders
Create Comparator objects for other criteria, either as classes, lambdas, or with Comparator.comparing(Type::getField).
Step 4
Sort with a comparator
Pass the comparator to list.sort(cmp) or Collections.sort(list, cmp) to override the natural ordering for that call.
Step 5
Chain and reverse
Combine criteria with thenComparing() and flip direction with reversed() to build multi-key sorts fluently.
What Interviewer Expects
- Comparable is internal (compareTo), Comparator is external (compare)
- Comparable defines one natural ordering per type
- Comparator allows multiple, swappable orderings
- Comparator works on classes you cannot edit
- Familiarity with comparing(), thenComparing(), and reversed()
Common Mistakes
- Swapping which interface uses compareTo() vs compare()
- Returning true/false instead of a negative/zero/positive int
- Implementing compareTo() inconsistently with equals()
- Using subtraction on ints that can overflow instead of Integer.compare()
- Thinking a class can have multiple Comparable orderings
Best Answer (HR Friendly)
“Comparable is the built-in default way a type sorts itself, like ordering people by ID. Comparator is a separate set of rules you supply to sort the same items another way, like by name or age, without changing the original class.”
Code Example
import java.util.*;
class Employee implements Comparable<Employee> {
String name;
int age;
Employee(String name, int age) { this.name = name; this.age = age; }
// Natural ordering: by age
@Override
public int compareTo(Employee other) {
return Integer.compare(this.age, other.age);
}
@Override
public String toString() { return name + "(" + age + ")"; }
}
public class SortDemo {
public static void main(String[] args) {
List<Employee> staff = new ArrayList<>(List.of(
new Employee("Asha", 30),
new Employee("Ravi", 25),
new Employee("Meera", 30)));
Collections.sort(staff); // uses Comparable: by age
System.out.println(staff);
// Comparator: by name, then by age descending
staff.sort(Comparator.comparing((Employee e) -> e.name)
.thenComparing(e -> e.age, Comparator.reverseOrder()));
System.out.println(staff);
}
}Follow-up Questions
- How does compareTo() signal ordering with its return value?
- Why should compareTo() be consistent with equals()?
- How do you sort by multiple fields using Comparator?
- When would you use Comparator over Comparable?
- Why prefer Integer.compare() over subtracting two ints?
MCQ Practice
1. Which method does the Comparable interface define?
Comparable declares compareTo(T other); Comparator declares compare(T a, T b).
2. You need to sort a third-party class you cannot modify. What do you use?
Comparator is external, so you can define orderings for classes whose source you cannot change.
3. What should compareTo() return when this is greater than other?
compareTo() returns a positive int when this is greater, negative when smaller, and zero when equal.
Flash Cards
Comparable method? — compareTo(T other), implemented inside the class to define its natural ordering.
Comparator method? — compare(T a, T b), defined outside the class to provide alternative orderings.
How many natural orderings can a type have? — One, via Comparable; unlimited alternatives via different Comparators.
Chain sort keys? — Use Comparator.comparing(...).thenComparing(...) and reversed() for multi-key ordering.