Comparable and Comparator are interfaces used in Java for sorting objects. Comparable defines the natural ordering of objects within the class itself, while Comparator provides custom sorting logic outside the class. Comparator is more flexible because it allows multiple sorting strategies for the same object.
Consider an Employee class. If employees are usually sorted by employee ID, Comparable can define that natural ordering. If employees sometimes need to be sorted by name or salary, Comparator can be used.
// Comparable 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 this.id - other.id;
}
}
// Comparator Example
import java.util.Comparator;
class NameComparator implements Comparator<Employee> {
@Override
public int compare(Employee e1, Employee e2) {
return e1.name.compareTo(e2.name);
}
}A concise interview answer is
Comparable is used to define the natural ordering of objects and is implemented within the class using the compareTo() method. Comparator is used for custom sorting and is implemented separately using the compare() method. Use Comparable when a class has one logical sorting order and Comparator when multiple sorting orders are needed.
Last updated: 16 July 2026
Previous question: When would you use an interface, and when would you use an abstract class?
Next question: What is a static method in an Interface, and how is it different from a default method in an interface?