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.
Key Points: • Comparable is implemented by the class whose objects need to be sorted. • Comparator is implemented in a separate class or using a lambda expression. • Comparable supports only one natural sorting order. • Comparator supports multiple custom sorting orders. • Comparable contains compareTo() method, whereas Comparator contains compare() method. • Comparator is preferred when different sorting criteria are required.
Example: 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.
Code Example:
// 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);
}
}Comparison:
Comparable: • Package: java.lang • Method: compareTo() • Sorting Logic: Inside the class • Number of Sort Orders: One • Modifies Class: Yes
Comparator: • Package: java.util • Method: compare() • Sorting Logic: Outside the class • Number of Sort Orders: Multiple • Modifies Class: No
When to Use Comparable:
• When objects have a single natural ordering • When the sorting logic belongs to the class itself • Example: Sorting Employees by Employee ID
When to Use Comparator:
• When multiple sorting criteria are required • When the source code of the class cannot be modified • Example: Sorting Employees by Name, Salary, or Department
Interview Tip: 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."