Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the diff between Comparator and Comparable

 
Chandra Bairi
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can anyone tell me java.lang.Comparable and java.util.Comparator
Thanks
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Comparator is an object that compares other objects, but has no interesting value itself. You could use a single Comparator to sort an array of Person objects.
A Comparable is an object that can be compared to other objects using a compareTo() method. Some API classes like Integer and String implement this interface. You can sort an array of these without supplying a Comparator, sinc e they know how to compare themselves to each other.
 
Chandra Bairi
Ranch Hand
Posts: 152
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can you give an example Mr.Hill. Thanks for the reply as well.
 
Joel McNary
Bartender
Posts: 1840
Eclipse IDE Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
A Comparable would be a String -- it comes with a default sort order (A, B, C, D, E, ...)
A comperable would be a class that you write to implement sorting on non-Comparable objects, or to provide sorting other than the default of a Comparable object.
For example, say that I decided that I wanted to "alphabetize" a collection of string not be the standard Roman alphabet but by the "QWERTY" keyboard alphabet. I would write a Comperable object to do this.
-------------
(This is an example that comes to mind because my three-year-old son now sings, to the tune of "Twinkle, Twinkle, Little Star"/"The Alphabet Song" :
"Q W E R T Y,
U I O P A S D.
F G H J K L Z.
X C V B N and M.
Now I know ny keyboard keys,
Next time won't you sing with me...."
of course, I made sure that he knows that alphabet both ways... )
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's an instance of "inheritance vs. delegation".
Using the Comparable interface, you use inheritance to put the compareTo method directly into the object you want to compare.
Using the Comparator interface, you delegate to an outside object implementing the compare strategy (see Strategy pattern).
The latter is both more flexible and more complex.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic