This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Difference between Comparable vs comparator?  RSS feed

 
Guna sekar
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Campbell Ritchie
Marshal
Posts: 55751
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Winston
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!