This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Question about Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Question about Comparator" Watch "Question about Comparator" New topic

Question about Comparator

Brian Legg
Ranch Hand

Joined: Nov 07, 2008
Posts: 488
I read something interesting saying that if your object is not modifiable (final) then you must use Comparator to sort them in a collection.

Why can't you use Comparable? Is it as simple as the final object can't implement Comparable, or is there something going on behind the scenes I should know?


~Currently preparing for SCJP6
patrick avery
Ranch Hand

Joined: Sep 12, 2008
Posts: 46
I think it is because Comparator is implemented as a separate class so you don't need to be able to modify the object being sorted, whereas Comparable must be implemented as a method in the class being sorted...hard to do if you can't modify the object.

SCJA 96%
SCJP 6 88%
skipping SCJD to work on passing SCWCD
Brian Legg
Ranch Hand

Joined: Nov 07, 2008
Posts: 488
True true... I always just assume that whatever object you are going to sort is known upfront and/or you can change the code.

Obviously that is a bad assumption. Thanks, makes since!
subject: Question about Comparator
It's not a secret anymore!