This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
A Comparator is an object that compares other objects, but has no interesting value itself. You could use a single Comparator to sort an array of Person objects. A Comparable is an object that can be compared to other objects using a compareTo() method. Some API classes like Integer and String implement this interface. You can sort an array of these without supplying a Comparator, sinc e they know how to compare themselves to each other.
A Comparable would be a String -- it comes with a default sort order (A, B, C, D, E, ...) A comperable would be a class that you write to implement sorting on non-Comparable objects, or to provide sorting other than the default of a Comparable object. For example, say that I decided that I wanted to "alphabetize" a collection of string not be the standard Roman alphabet but by the "QWERTY" keyboard alphabet. I would write a Comperable object to do this. ------------- (This is an example that comes to mind because my three-year-old son now sings, to the tune of "Twinkle, Twinkle, Little Star"/"The Alphabet Song" : "Q W E R T Y, U I O P A S D. F G H J K L Z. X C V B N and M. Now I know ny keyboard keys, Next time won't you sing with me...." of course, I made sure that he knows that alphabet both ways... )
Piscis Babelis est parvus, flavus, et hiridicus, et est probabiliter insolitissima raritas in toto mundo.
It's an instance of "inheritance vs. delegation". Using the Comparable interface, you use inheritance to put the compareTo method directly into the object you want to compare. Using the Comparator interface, you delegate to an outside object implementing the compare strategy (see Strategy pattern). The latter is both more flexible and more complex.
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus