What is the difference between Comparable and Comparator in Java?
They are two different ways of saying which of two things should come first, and they live in different places.
A class that implements Comparable says what its own natural order is. The order is built into the class, and the class is the only thing that knows it. A Comparator is a separate object that knows how to order two things, and you can write as many of them as you like.
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("Charlie");
names.add("Alice");
names.add("Bob");
// The natural order of a string.
Collections.sort(names);
System.out.println("sorted normally : " + names);
// A different order, given from outside.
Comparator<String> byLength = new Comparator<String>() {
public int compare(String first, String second) {
return first.length() - second.length();
}
};
Collections.sort(names, byLength);
System.out.println("sorted by length : " + names);
}
}
There are three practical differences.
The first one is where the order lives. The natural order is inside the class, so every list of that type is sorted the same way without asking. A comparator is chosen at the point where you sort.
The second one is how many you can have. A class can implement Comparable only once, because there is only one natural order. You can have as many comparators as you want, and they can be passed around as values.
The third one is what happens when the class is not yours. If somebody else wrote the class, you cannot make it implement Comparable, but you can always write a comparator for it.
The next question in this topic looks at the first difference more closely.