What is the difference between Comparable and Comparator in Java?
Comparable defines one natural order inside the class itself through compareTo. Comparator is a separate object with a compare method, so you can define many different orderings without changing the class.
Explain it simply
Students in a class have a natural order, say by roll number, which belongs to the student record itself: that is Comparable. But the teacher may also line them up by height for a photo, or by marks for a result: those outside rules are Comparators.
Example
import java.util.*;
class Student implements Comparable<Student> {
int roll; String name;
Student(int roll, String name) { this.roll = roll; this.name = name; }
public int compareTo(Student o) { return Integer.compare(roll, o.roll); } // natural order
}
List<Student> list = new ArrayList<>(List.of(new Student(3, "Asha"), new Student(1, "Zoya")));
Collections.sort(list); // by roll: Zoya, Asha
list.sort(Comparator.comparing(s -> s.name)); // by name: Asha, ZoyaWhat to say in the interview
"Comparable is in java.lang and has compareTo(T). The class has only one natural ordering, and it must modify the class. Comparator is in java.util and has compare(T, T). I can create as many as I like, and even sort classes I cannot edit, such as String by length. In Java 8, I build comparators with Comparator.comparing and thenComparing."
Common mistakes
- Writing
a.roll - b.rollin compareTo, which can overflow for big values. Use Integer.compare.