Java Core & JVM (50 Qs)•Part 1: Core Language, Memory Model & Collections (1 - 10)
What is the difference between `Comparable` and `Comparator`?
junior LevelCode ExamplejavaCore Language
In Simple Words:
Comparable<T>: Defines natural ordering inside the class itself viaint compareTo(T o). Modifies class code.Comparator<T>: Defines custom, pluggable sorting strategies external to the class viaint compare(T o1, T o2).
java
public record Employee(int id, String name, double salary) implements Comparable<Employee> {
@Override
public int compareTo(Employee other) {
return Integer.compare(this.id, other.id); // Natural order by ID
}
}
// Custom Comparators using lambdas:
Comparator<Employee> bySalaryDesc = Comparator.comparingDouble(Employee::salary).reversed();
Comparator<Employee> byNameThenSalary = Comparator.comparing(Employee::name)
.thenComparingDouble(Employee::salary);