Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparable and Comparator" Watch "Comparable and Comparator" New topic
Author

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
Sheriff

Joined: Oct 27, 2005
Posts: 19655
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Chandra Bhatt
Ranch Hand

Joined: Feb 28, 2007
Posts: 1707
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


cmbhatt
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38049
    
  22
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!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Comparable and Comparator
 
Similar Threads
Interface
Difference in between comparable and comparator interface
sorting of a list having bean object
difference between Comparator and Comparable interface
Sort a list