Originally posted by Smita Chopra:
What is the difference between Comparable and Comparator interface?
To me it looks like both are used for specifying the natural order for objects.
Thanks
Class that implement these two interfaces are used for different roles in the ordering process. Objects of a class that implement Comparable are the things that get sorted, while a Comparator is a wrapper for a compare() method used in sorting.
For instance, we might define a PlayingCard class that implements Comparable. The compareTo() method that it defines might order the
cards the way they come from a particular manufacturer: A-2 of Spades, A-2 of Hearts, A-2 of Clubs, A-2 of Diamonds, Joker1, Joker2.
However, for a GoFish game I'm writing I may want the
cards in my hand sorted in a different order: by rank first (Aces count as ones) with suits (in alphabetical order) breaking ties. To support this I'd define a FishSorter class that implements Comparator. This would define a compare() method that takes two PlayingCard objects. (Of course, to be safe, compare() should check the type of the objects to verify they're PlayingCards.)
Then when I want to sort the ArrayList (which implements List) of PlayingCards in my hand, I pass that ArrayList and a FishSorter object to the static Collections.sort(List, Comparator) method. Then I'll have my hand sorted in GoFish order.
The point is that while PlayingCard defines one compareTo() method that imposes one ordering, I can have a whole bunch of Comparators for PlayingCards that imposes different orderings for different situations. I might have a FishSorter, a BridgeSorter, a SkatSorter, a BigTwoSorter, etc. That way I don't have to modify the basic PlayingCard class just because Big Two ranks 2's above Aces. (Maybe for the BridgeSorter, I use the current trump suit as an argument to the constructor so that the order of suits in my ordering varies depending on the current trump suit.)
Cool?