Java
Comparable vs Comparator in Java Collections
By Utility Zone · 2026-02-16T15:59:58.501608
1. Comparable (Natural Ordering)
Definition
Comparable is an interface in java.lang used to define the natural
ordering of objects.
Method
int compareTo(T o);
Example
class Employee implements Comparable<Employee> {
int id;
String name;
Employee(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public int compareTo(Employee other) {
return Integer.compare(this.id, other.id);
}
}
Sorting
Collections.sort(employeeList);
Key Points
- Sorting logic is inside the class
- Only one natural ordering allowed
- Used automatically by TreeSet and TreeMap
2. Comparator (Custom Ordering)
Definition
Comparator is an interface in java.util used to define custom
sorting logic outside the class.
Method
int compare(T o1, T o2);
Example
Comparator<Employee> nameComparator =
Comparator.comparing(Employee::getName);
employeeList.sort(nameComparator);
Multiple Sorting Criteria
Comparator<Employee> comparator =
Comparator.comparing(Employee::getName)
.thenComparing(Employee::getId);
employeeList.sort(comparator);
Key Points
- Sorting logic is external
- Multiple sorting strategies supported
- Preferred in modern Java (with lambdas)
Comparison Table
Feature Comparable Comparator
Package java.lang java.util Method compareTo() compare() Sorting Logic Inside class Outside class Multiple sorting No Yes Used by TreeSet default Yes If provided
Important Interview Insights
1. Avoid Subtraction in compareTo
return this.salary - other.salary; // Risk of overflow
Use instead:
return Integer.compare(this.salary, other.salary);
2. Consistency with equals()
If compareTo() returns 0, ideally equals() should also return true to avoid issues in sorted collections.
3. Sorting Complexity
- Collections.sort() → O(n log n)
- TreeSet insertion → O(log n)
Final Summary
Comparable → Natural ordering → compareTo()
Comparator → Custom ordering → compare()
Use Comparable for default identity ordering.
Use Comparator for flexible business-based sorting.