what is the difference between comparable and comparator? Suppose if you want to sort an object based on two criterias( say name, id) based upon user input, how do we implement it? which one should be used? which is better?
Try this thread and this one. See whether they help. Ask again if there is something you don’t understand.
If you have a class with dateOfBirth fields, lastName and firstName, sorting on date of birth, then first name, then last name, with a stable sorting algorithm will get your list into this sort of order:-
Ritchie, Campbell 12-3-45
Ritchie, Campbell 23-4-56
Ritchie, Carol 1-1-89
Ritter, Andrew 11-1-42
Guna sekar wrote:what is the difference between comparable and comparator? Suppose if you want to sort an object based on two criterias( say name, id) based upon user input, how do we implement it? which one should be used? which is better?
First: It's Comparable and Comparator. You're in for a lot of frustration unless you remember that Java is case-sensitive.
Second: You don't sort an object, you sort objects. An object may, however, have an order, which is where Comparator and Comparable come in.
Third: What do you mean by "based on user input"? Do you mean that the user gets to choose at runtime how the objects are sorted? If so, you might want to create some sort of ComboComparator<T> class that accepts a set of Comparator<T>'s and applies them in sequence.
I've actually created a class called Index, which does exactly that, along with a class called NaturalOrder that encapsulates the natural order of a Comparable class as a Comparator. Both very useful.
"Leadership is nature's way of removing morons from the productive flow" - Dogbert
Articles by Winston can be found here
Make yourself as serene as a flower, as a tree. And on wednesdays, as serene as this tiny ad: