I have seen classes which implement both Comparable and Comparator. What does this mean? Why would I use one over the other?
Comparable
is for objects with a natural ordering. The object itself knows how it is to be ordered.
Comparator
is for objects without a natural ordering or when you wish to use a different ordering.
Comparable
is for providing a default ordering on data objects, for example if the data objects have a natural order.
A Comparator
represents the ordering itself for a specific use.
The text below comes from Comparator vs Comparable
Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable
interface in order to be able to compare its instances.
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator
interface.
Implementing Comparable
means "I can compare myself with another object." This is typically useful when there's a single natural default comparison.
Implementing Comparator
means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.
Difference between Comparator and Comparable interfaces
Comparable
is used to compare itself by using with another object.
Comparator
is used to compare two datatypes are objects.