A friendly place for programming greenhorns!
Big Moose Saloon
Register / Login
Win a copy of
Java 8 in Action
this week in the
Comparable and Comparator
Joined: Sep 03, 2008
Sep 13, 2008 04:39:00
other than having compareTo() and Compare() methods
whats the actual difference between Comparable and Comparator interface?
i think both ar doing the same thing..
Joined: Oct 27, 2005
Sep 13, 2008 06:58:00
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
Joined: Feb 28, 2007
Sep 13, 2008 07:35:00
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
Joined: Oct 13, 2005
Sep 13, 2008 08:23:00
Do a search for "comparable comparator" and you find
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
difference between Comparator and Comparable interface
Sort a list
Difference in between comparable and comparator interface
sorting of a list having bean object
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
| Powered by
Copyright © 1998-2014