Comparable is an interface implemented by classes that can compare themselves with another instance of this class.
Comparator is an interface for comparing two instances of another class.
If you have a Person class, for example
public class Person implements Comparable<Person> { private final String firstName; private final String lastName; ... public int compareTo(Person that) { int rv = lastName.compareTo(that.lastName); if (rv == 0) rv = firstName.compareTo(that.firstName); return rv; } }
This is a class that has a natural sort order by last name, and then by first name, i.e. Stephen Jones comes to John Smith.
If you wanted to sort these objects by first name and then last name so that John Smith came up with Stephen Jones, you would use the Comparator
public class PersonComparator implements Comparator<Person> { public int compare(Person p1, Person p2) { int rv = p1.getFirstName().compareTo(p2.getFirstName()); if (rv == 0) rv = p1.getLastName().compareTo(p2.getLastName()); return rv; } }
What you use depends on what control you have over classes and instances.
For example, if you have a class that does not implement Comparable , but you can subclass it to implement the interface, and you are sure that you will be the only person creating instances, then you can use Comparable .
In general, however, Comparator is more flexible.
source share