posted 14 years ago
To be able to use the Comparable interface, the class of the objects in the collection has to implement that interface. You might have for example a List of objects from a class that you don't control yourself - for example, a class that comes from some third-party library. You can't make that class implement Comparable easily (it would mean you'd have to change the source code of the third-party library, which is normally not a good idea).
To be able to sort the List anyway, you can implement your own Comparator and pass that to for example Collections.sort(list, comparator);. Your Comparator object can be separate from the objects that are in the List.
Another example is when you might want to sort the list in different ways. Suppose you have a Person class:
Suppose that you have a List of Person objects, and that you at one time want to sort the List by name, but at another time sort the List by age. You could make class Person implement Comparable, but you can implement the compareTo() method in only one way.
By using Comparator, you could instead make different comparators, one that compares Person objects by name, and another one that compares them by age. If you want to sort by name, you use the first Comparator object, and if you want to sort by age you use the other Comparator object.