What is difference in Comparator and Compareable interface. Please also explain following line "Objects can specify thier natural order by implementing the Compareable interface, or be dictated a total order by comparator which implements the Comparator interface."
Any one can please explain with example
"Know where to find the solution and how to use it - that's the secret of success."
Comparable interface imposes a total ordering on the objects of the class that implements it. This is done using the compareTo method. Lists (and arrays) of objects that implement this interface can be sorted automatically by Collections.sort (and Arrays.sort).
Comparator can be passed to a sort method (such as Collections.sort) to allow control over the sort order and give you the capability to sort a given collection any number of different ways. A comparator class is solely built often to serve a a sorting aid to OTHER classes based on the criterion defined.
Look at the DVD example in K&S Pg.554. where the DVDInfo implements comparable to sort dvds based on title, and then a comparator class is defined, an object of which is passed to the Collections.sort method to sort based on genre.
If you follow the links within the link wise owen provided above, you'll find a note on what helped me with the distinction:
"Comparable" is an adjective. So if an object is Comparable, that means it can be compared to other objects. Note that the method compareTo(Object o1) takes a single argument -- a reference to the object that the Comparator ("this") is being compared to.
"Comparator" is a noun. Specifically, it is an object used to compare other objects. Note that the method compare(Object o1, Object o2) takes two arguments -- ordered references to the objects being compared to each other.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org