• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Comparable and Comparator

 
Ranch Hand
Posts: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Bartender
Posts: 1845
10
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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: 172
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Ok Thanks.
 
Marshal
Posts: 79177
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic