They are not interchangeable . A good example is Comparable
vs Comparator
in the JDK.
In your case, Comparable
represents the implementing-an-interface design. Comparator
is an example of the strategy pattern. With the two signatures of Collections.sort
, you can do this
Collections.sort(listOfComparables);
or this
Collections.sort(anyList, comparator);
Imagine you have a list of Car
s. You might want to sort the list by colour, by number of seats, by horsepower. In this case, it makes no sense to implement Comparable
. Cars have no natural ordering; it makes no sense to give preference to one ordering over another by implementing the interface. In this case, all orderings are created equal. If you were to declare a car as Comparable
then it would likely not be very intuitive for users of your class. They would probably have to check the implementation or the documentation to work out what order you had intended. You should sort these using Comparator
s.
Now imagine you have a list of Coin
s. Coins have a fairly obvious natural ordering: their face value. You could sort your coins by size, or by weight, but their primary reason for existing is to represent different denominations. In this case, not all orderings are created equal. It would make sense here to implement Comparable
, and if other orderings are required, you can use Comparator
s for that.
In a more general sense, the strategy pattern is often best applied when there is no one "preferred" approach. A class can only implement an interface once, but it may be able to make use of many different strategies. It is a kind of inversion of control.