• Post Reply Bookmark Topic Watch Topic
  • New Topic

Comparable and Comparator  RSS feed

 
Alan Blass
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi!

I want to know when to use comparable and comparator.

A lot of website I searched tell me use comparable for natural ordering, which is used for id.

What if I need to sort by name? They tell me to use comparator. Is that natural ordering too?

Please advise. Thanks.
 
Stefan Evans
Bartender
Posts: 1837
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main difference between them can be found in the java API.

java.lang.Comparable - oneObject.compareTo(otherObject);
vs
java.util.Comparator - comparator.compare(oneObject, otherObject)

Can you see the fundamental difference between them just by looking at these method signatures?

In a nutshell comparable is for the "natural" ordering. It applies directly to the class. The class can only implement comparable once, so you can only have one ordering defined this way, hence the recommendation to use the "natural" ordering.
You can define as many comparators as you like for a class, all giving different orderings.

For instance if you had a class "Item" with attributes id, name and price.

You could define Comparable to sort on id.
You could have comparators if at any point you want to sort by any of the other fields. e.g .price.
 
Alan Blass
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok Thanks.
 
Campbell Ritchie
Marshal
Posts: 56546
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Go through the Java® Tutorials about Collections; in the second section about interfaces there is a page about object ordering. You will find more useful information there.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!