Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparable vs Comparator

 
Garlapati Ravi
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In K&B i have a seen a statement
Only one sort sequence can be created - Comparable
Many sort sequences can be created - Comparator

I don't understand how can we create many sort sequences using Comparator. can anyone clarify please.
Consider below code, how we can create many sort sequces in it, at a time we can implement compare method once,as we can't over load it, if we want to create other sequence, we need to change return statement ? in that case why they have used "Many" for Comparator and "one" sequences for Comparable
 
Henry Wong
author
Marshal
Pie
Posts: 21216
81
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Basically, a comparable allows a data element to compare itself to another element, while a comparable can compare any two elements. You can create as many comparators as you like, with different sorting algorithms, but your data element can only implement one comparable interface.

In your case, you can create a GenreSort, an AuthorSort, an LeadActorSort, etc, for your DVDinfo class. But, you can only have your DVDinfo class implement Comparable once.

Henry
 
Garlapati Ravi
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
that makes sense. thanks a lot!
 
Atwal Usha
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't understand how can we create many sort sequences using Comparator. can anyone clarify please.


Henry has already explained it very well. I would like to add that comparators are created as different classes and you can create as many different classes implementing Comparator and use them for sorting purpose however your class can implement only one Comparable interface.

 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic