It's not a secret anymore!
The moose likes Beginning Java and the fly likes Comparable and Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCA Java SE 8 Programmer I Study Guide this week in the OCAJP 8 forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparable and Comparator" Watch "Comparable and Comparator" New topic

Comparable and Comparator

geet kaur
Ranch Hand

Joined: Sep 03, 2008
Posts: 78
other than having compareTo() and Compare() methods
whats the actual difference between Comparable and Comparator interface?
i think both ar doing the same thing..
Rob Spoor

Joined: Oct 27, 2005
Posts: 20131

They are. However, sometimes you want to use a different kind of ordering, and ignore the compareTo method. Or the objects you want to sort are not Comparable and you can't make them Comparable. If either is the case, you have to use a Comparator.

How To Ask Questions How To Answer Questions
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1710
Comparator is widely used when you need multiple sortings as sorting on one field for one requirement and sorting on another field for different requirement.

See this link: Custom sorting, on the fly as per requirement

Example of using Comparable & Comparator for sorting

Campbell Ritchie

Joined: Oct 13, 2005
Posts: 44515
Do a search for "comparable comparator" and you find this, this, this, this and lots more.

I shall let you read those links to see whether they are any good!
I agree. Here's the link:
subject: Comparable and Comparator
It's not a secret anymore!