aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparable vs Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparable vs Comparator" Watch "Comparable vs Comparator" New topic
Author

Comparable vs Comparator

Garlapati Ravi
Ranch Hand

Joined: Mar 05, 2008
Posts: 171
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


Ravi Kumar
SCWCD 5 - 89%, SCJP 1.4 - 90%
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 19073
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Garlapati Ravi
Ranch Hand

Joined: Mar 05, 2008
Posts: 171
that makes sense. thanks a lot!
Atwal Usha
Ranch Hand

Joined: Sep 10, 2009
Posts: 137
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.


Java Certification Exam Mock Tests: SCJA  SCJP 5  SCJP 6  SCJP 6 (Online Training)  SCJP 6 (Instructor Led Training)   SCWCD 5   SCBCD 5  SCEA 5
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparable vs Comparator