File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
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
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: 19692
    
  20

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: 38765
    
  23
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: http://aspose.com/file-tools
 
subject: Comparable and Comparator