Prerequisites
- Basic Java knowledge
System Requirements
- JDK installed
What are Java Comparators and Comparables?
As both names suggest (and you may have guessed), these are used for comparing objects in Java. Using these concepts; Java objects can be sorted according to a predefined order.Two of these concepts can be explained as follows.
Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.Do we need to compare objects?
The simplest answer is yes. When there is a list of objects, ordering these objects into different orders becomes a must in some situations. For example; think of displaying a list of employee objects in a web page. Generally employees may be displayed by sorting them using the employee id. Also there will be requirements to sort them according to the name or age as well. In these situations both these (above defined) concepts will become handy.How to use these?
There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user. Those are;java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
- positive – this object is greater than o1
- zero – this object equals to o1
- negative – this object is less than o1
This method compares o1 and o2 objects. Returned int value has the following meanings.
- positive – o1 is greater than o2
- zero – o1 equals to o2
- negative – o1 is less than o2
Sorting with Collections class
- java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
- java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.
public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values on attributes
}
// getters & setters
}
import java.util.*;
public class Util {
public static List<Employee> getEmployees() {
List<Employee> col = new ArrayList<Employee>();
col.add(new Employee(5, "Frank", 28));
col.add(new Employee(1, "Jorge", 19));
col.add(new Employee(6, "Bill", 34));
col.add(new Employee(3, "Michel", 10));
col.add(new Employee(7, "Simpson", 8));
col.add(new Employee(4, "Clerk",16 ));
col.add(new Employee(8, "Lee", 40));
col.add(new Employee(2, "Mark", 30));
return col;
}
}
Sorting in natural ordering
Employee’s natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.public class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;
/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(Employee o) {
return this.empId - o.empId ;
}
// ….
}
We’ll write a class to test this natural ordering mechanism. Following class use the Collections.sort(List) method to sort the given list in natural order.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
Collections.sort(coll); // sort method
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
EmpId Name Age
1 Jorge 19
2 Mark 30
3 Michel 10
4 Clerk 16
5 Frank 28
6 Bill 34
7 Simp 8
8 Lee 40
Sorting by other fields
If we need to sort using other fields of the employee, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll loose this empId based sorting mechanism. This is not a good alternative if we need to sort using different fields at different occasions. But no need to worry; Comparator is there to save us.By writing a class that implements the java.util.Comparator interface, you can sort Employees using any field as you wish even without touching the Employee class itself; Employee class does not need to implement java.lang.Comparable or java.util.Comparator interface.
Sorting by name field
Following EmpSortByName class is used to sort Employee instances according to the name field. In this class, inside the compare() method sorting mechanism is implemented. In compare() method we get two Employee instances and we have to return which object is greater.public class EmpSortByName implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}
private static void printList(List<Employee> list) {
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
EmpId Name Age
6 Bill 34
4 Clerk 16
5 Frank 28
1 Jorge 19
8 Lee 40
2 Mark 30
3 Michel 10
7 Simp 8
Sorting by empId field
Even the ordering by empId (previously done using Comparable) can be implemented using Comparator; following class does that.public class EmpSortByEmpId implements Comparator<Employee>{
public int compare(Employee o1, Employee o2) {
return o1.getEmpId() - o2.getEmpId();
}
}
Explore further
Do not stop here. Work on the followings by yourselves and sharpen knowledge on these concepts.- Sort employees using name, age, empId in this order (ie: when names are equal, try age and then next empId)
- Explore how & why equals() method and compare()/compareTo() methods must be consistence.
You should also try to handle null values.
ReplyDeleteWhen dealing with comparable and comparator NPE is near far.
DeleteTrue, there will be situations where you caught up with NPE. But I don't think this responsibility is bound to Comparator or Comparable.
For example; if we are using String class to sort, it's our duty to deal with the 'null' values. String class will through NPE if 'null' values used.
But it would be good if we could handle that as well.
And just to complete the example, a manually defined comparator:
ReplyDeletebyNameLength = { a, b -> a.name.size() <=> b.name.size() } as Comparator
pretty employees.sort(byNameLength)
this is good just what I looked for.
ReplyDeletecheers
Nimch
The context in which comparable or comparator should be used is pretty clear, good tutorial
ReplyDeleteExactly what I was looking for to get ready for exam
ReplyDeleteThank you very much
This tutorial is short, concise and crystal clear.
ReplyDeleteI'm a undergraduate student learning Java and this helped me set some things I didn't understand straight.
Thanks !
Nice one. Very helpful...
ReplyDeleteThis is very helpful.
ReplyDeleteGood example.
ReplyDeleteBut this code working just for Java 5 and higher .
But for some reason I need to use Java 1.4. Next the same code for Java 1.4: It looks like:
1. public class Employee implements Comparable{
2. public int compareTo(Object o) {
Employee e = new Employee();
e = (Employee)o;
return this.empId - e.getEmpId() ;
3. public class EmpSortByName implements Comparator{
public int compare(Object o1, Object o2) {
Employee e1 = new Employee();
e1 = (Employee)o1;
Employee e2 = new Employee();
e2 = (Employee)o2;
return e1.getName().compareTo(e2.getName());
Thanks
Igor Chirokov
1.In this list I have multiple elements and I'm needing to sort by 2 elements within this list: first by binSortCode and then by itemDescr
ReplyDeleteI've been googling and trying to get some help but am having problems trying to understanding comparable vs comparator. I had used comparable to sort on a single element and it worked find but when trying to sort on multiple elements I'm not able to make it work.
I have created a comparator class where I am trying to sort first on binSortCode and then sort on itemDesc, please see the following:
public class CommonListItemSort implements Comparator$ltCommonListItem>{
2.
3. //Sort common list items by bin sort code then by item description
4. public int compare(CommonListItem o1, CommonListItem o2) {
5. int diff = o1.getBinSortCode().compareToIgnoreCase(o2.getBinSortCode());
6. if (diff == 0)
7. diff = o1.getItemDesc().compareToIgnoreCase(o2.getItemDesc());
8. return diff;
11. }
12. }
13.
14. I then call this class from my servicebean as follows:
15.
16. public CommonList getDetails(final String entityCode, final String commonListName) {
17. CommonList commonList = commonListDao.find(commonListName, entityCode);
18.
19. //Sort the items by binsortcode and then by item description
20. Collections.sort(commonList.getCommonListItems(), new CommonListItemSort());
21. return commonList;
22. }
The outcome that I'm getting is that binSortCode is in DESC order and itemDesc is in ASC order where in actuality I need the list to sort first by binSortCode ASC and then itemDesc in ASC.
Any help or direction would be greatly appreciated. Thanks.
return o1.getEmpId().compareTo(o2.getEmpId()); in class EmpSortByEmpId doesn't compile.
ReplyDeleteSolution : compare Strings !
return String.valueOf(o1.getEmpId()).compareTo(String.valueOf(o2.getEmpId()));
Real good thanks! Im getting ready for exam and this was so much clearer than the PDF we was handen. Cheers
ReplyDeleteTypo above:
ReplyDeletenegative – o1 is less than o1
should be
negative – o1 is less than o2
I'd like to add my thanks as well.
ReplyDeleteYour examples were very concise and clear. They helped me actually implement Comparator as opposed to just understanding the theory.
Thanks, Really a good tutorial.
ReplyDeleteThanks, Its really good artical to understand and well explained.
ReplyDeleteit was very usefull....thanks a lot
ReplyDeleteGood one was very useful!
ReplyDeleteappreciate ur effort !
very nice!
ReplyDeletethank you!
very nice and clean!
ReplyDeleteThank You very much.
it very clear thank u very much
ReplyDeleteGood tutorial ,
ReplyDeleteHowever on execution of the code gives me "Class Cast Exception" ,
java.lang.ClassCastException: com.Comparator.Employee cannot be cast to java.lang.Comparable
Can anyone suggest
this really helped
ReplyDeleteNice one !!! It would be helpful to everyone
ReplyDeleteThis was the best article. Very, very helpful, nice and clean.
ReplyDeleteExcellent explanation, thanks much.
ReplyDeleteDon
easy, concise, simple and an accurate example. Thanks Kamal
ReplyDeleteHe has written a very good article . Instead of pointing out mistakes , appreciate his efforts & provide better suggestions. Great Job
ReplyDeleteThanks a lot. Very useful tutorial. Vladimir
ReplyDeleteVery nice,easily understandable,
ReplyDeleteand please give the why we have to override hashcode() method.
To the point and precise. Great work!!
ReplyDeleteThis tutorial was fantastic. I knew I needed to use a Comparator, but it's been a long time since I last did one. This information was exactly what I needed to get the job done and jogged my brain again.
ReplyDeleteThank you and keep the tutorials coming!
you have written in definition of the Comparator that it belongs to java.lang.comparator but it is wrong and instead it belongs to java.util.comparator;
ReplyDeletethanks for a clean tutorial. I get it now !
ReplyDelete-Omaha, Nebraska (USA)
Is there any way to include more than one method in a single class, rather than creating single compare method in one class
ReplyDeletenice explaination! Just one correction - Comparator interface is under java.util package and not under java.lang
ReplyDeleteThank you! I have been searching for hours how to sort my ArrayList and only your tutorial made me understand what I was doing wrong (my ArrayList was made of arrays, as in ArrayList«double[]»).
ReplyDeleteA well written tutorial, thanks again!
Good example............. Yeah I got the point.. Thank you very much :) cheers
ReplyDeletereally nice explanation.. hats off
ReplyDeletegood article! thanks!
ReplyDeleteveeeeeeeeeeerrrrrry helpful, thorough, and well written, thanks.
ReplyDeleteAllasso
Thanks for your effort!It is really good!
ReplyDeleteHowever ,I found that the last part "Sorting by empId field" does not work !
I have to cast the int into String first,
public class EmpSortByEmpId implements Comparator{
public int compare(Employee o1, Employee o2) {
String myStringO1 = Integer.toString(o1.getEmpId());
String myStringO2 = Integer.toString(o2.getEmpId());
return myStringO1.compareTo(myStringO2);
}
// 42
ReplyDeleteHi fan,
You will not need to convert int values to Strings in this example as Java5 does auto-boxing.
The explanation is super. thanks.
ReplyDeleteThis really helped in my preparation about Comparable and Comparator. Well framed I book marked.
ReplyDeleteHi,
ReplyDeleteVery Nice article..It made me very clear abt the Comparable and Comparator interface.. I had checked few sites..but there was no clear info as you have provided.. Thanks
Thank you for taking the time to publish this, it was very clear. The best basic tutorial on comparator I have seen!
ReplyDeleteThank you so much ! I found what I was looking for !!
ReplyDeleteThanks From Paris (France).
Your post help me a lot.
ReplyDeletethanks from Brazil!
thank you . I from vietnamese
ReplyDeleteThank you....Very clearly explained
ReplyDeleteGood information in precise form
ReplyDeleteThanks, it helped me.
ReplyDeleteSimply simple in simple terms... the basic context of both interfaces is clear
ReplyDeletehi
ReplyDeletethax a lot dude...very useful tutorial....thanx again
ReplyDeletePrabhat
very nice... and helpful. thks biju
ReplyDeletehi can u plz tell me why equals() and compare()methods must be consistence
ReplyDeleteHello Kamal,
ReplyDeleteOne very important correction needs to be made to this post. Comparator belongs to the java.util package and not java.lang as you have mentioned in the beginning of the post. Please rectify as this a crucial thing to be overlooked.
regards,
Aparajeeta
this is very helpful tutorial. really good one
ReplyDeleteHello Kamal,
ReplyDeleteIt is simple and very helpful.
one Imp.note I too observed that the comparator interface is from java.util, but is is mentioned as from java.lang in the beginning (How to use these? section).
Thank you.
Santhosh
Very Clear. Thank You.
ReplyDeleteThanks for your effort!It is really good!
ReplyDeleteHowever ,I found that the last part "Sorting by empId field" does not work !
I have to cast the int into String first,
I'm Using java 1.5 , but it's not auto boxing. I mean int to String.
compateTo() method compares only Strings only
public class EmpSortByEmpId implements Comparator{
public int compare(Employee o1, Employee o2) {
String myStringO1 = Integer.toString(o1.getEmpId());
String myStringO2 = Integer.toString(o2.getEmpId());
return myStringO1.compareTo(myStringO2);
}
very good explain nation.Really Good..Keep up the Good Work Going....
ReplyDeleteI must read your other articles. Its nice article.
ReplyDeleteHere,Collections are used for comparing the different instances but....for the same class. Why so??
ReplyDeleteHi,
ReplyDeleteCan u plz tell me why equals() and compare()methods must be consistence??
Regards,
Bibhakar.
Great, to the point post. Nice way of covering too with good examples.
ReplyDeleteHi,
ReplyDeleteThe Comparator interface belongs to java.util.Hence please correct the article as java.util.Comparator.I think it is a typo.
This is excellence tutorial for beginners to understand the d/f b/w comparable and comparator...Excellent job
ReplyDeleteThis is really great tutorial with nice example. Thanx a lot
ReplyDeletewat's d difference between compare() and compareTo() methods
ReplyDeleteComparator belongs to util package.....Not to lang........
ReplyDeleteHi,
ReplyDeleteThere is a typo
java.lang.Comparator,
instead
java.util.Comparator
Hi all,
ReplyDeleteThanks for pointing the typo in package name of java.util.Comparator interface. Now it is corrected.
Thank you so much for the explanation and examples, its really helps me. Only that..i got error..java.lang.ClassCastException: java.lang.String cannot be cast to..when i tried to make sorting with integer by following example Sorting by empId field. Can anybody help me? Thank you.
ReplyDeleteI have menu order as string with levels separated with dot (for instance it will be like 1.2.1 and 1.2.2). This works fine with a sql order by when the last numbers are upto 9 but with 10 it comes as first. After i read ur article i was able to crack it.
ReplyDeleteThanks
Very clear explanation of how comparator and comparable work with nice examples, thank you so much and keep posting more articles like this.
ReplyDeleteExcellent example.. very well explained...`
ReplyDeletei have a problem with this code which most of it have almost same error.help me anyone
ReplyDeletepublic interface Comparable{
public int compareTo(Object o);
}
public class BinarySearch1{
public static final boolean contains(Comparable item, Comparable[] array, int n){
int low = 0;
int high = n - 1;
while (low <= high){
int mid = (low + high) / 2;
int compare = item.compareTo (array[mid]);
if (compare < 0){
high = mid - 1;
}
else if (compare > 0){
low = mid + 1;
}
else {
return true;
}
}
return false;
}
public static void main(String[]args){
BinarySearch1 value = new BinarySearch1();
Comparable[] array = new Comparable[4];
//array[0] = new Comparable();
// System.out.println(value.contains(3,array[1],4));
//System.out.println(value.contains(4));
}
}
really good one.. thanks a lot
ReplyDeleteThanks for this great explanation. I've always had trouble understanding the comparator mechanisms until now.
ReplyDelete('=')
ReplyDeleteReally Superb Explaination..
i searchd in many websites...i didnt seen this type of good explaination..
thank u very much
All izz well('=')
I was able to implement the same things. Thank you for this :)
ReplyDeleteThanks alot ...Very clear and easy to understand :)
ReplyDeleteI implemented the same code... It works
ReplyDeleteOne of THE best tutorial..
ReplyDeleteNice and simple tutorial, thanks!
ReplyDeletegood examples....
ReplyDeleteAwesome explanation, very useful contents.
ReplyDeleteI have one Employee Class and adding the Employee object in HashSet.
ReplyDeleteI am getting the Exception while trying to print the the HashSet in sorted order.
It works when i use compareTo() but throws exception "Employee cannot be cast to java.lang.Comparable" using compare(). Please help.
Below is the code:
public class Employee {
private String empID;
private String name;
private int salary;
Employee(String empID,String name,int salary){
this.empID=empID;
this.name=name;
this.salary=salary;
}
String getName(){
return name;
}
String getEmpID(){
return empID;
}
int getSalary(){
return salary;
}
public String toString(){
return empID + " " + name + " " + salary;
}
}
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
class EmpsortByName implements Comparator{
public int compare(Employee emp1, Employee emp2){
return ((emp1.getName()).compareTo(emp2.getName()));
}
}
class EmpsortByID implements Comparator{
public int compare(Employee emp1, Employee emp2){
return ((emp1.getEmpID()).compareTo(emp2.getEmpID()));
}
}
class EmpsortBySalary implements Comparator{
public int compare(Employee emp1, Employee emp2){
return emp1.getSalary()- emp2.getSalary();
}
}
public class EmployeeHashSet{
public static void main(String []asgs){
Set empset = new HashSet();
empset.add(new Employee("emp1011","Andrew", 30000));
empset.add(new Employee("emp1021","Stuart", 20000));
empset.add(new Employee("emp5043","Symond", 40000));
empset.add(new Employee("emp1010","Rob", 30700));
empset.add(new Employee("emp1020","Bill", 20900));
empset.add(new Employee("emp5053","Bill",41000));
TreeSet setlist=new TreeSet(empset);
Collections.sort(new ArrayList(setlist),new EmpsortByName());
Iterator iterator = setlist.iterator();
System.out.println("\\Employee names in sorted order::");
while(iterator.hasNext()){
Employee emp= (Employee)iterator.next();
System.out.println(emp.getName());
System.out.println(emp);
}
}
}
Ahh, this tutorial was so crystal clear, nice and small compared to the dreadfully long and complex code examples in my thick java book. Thank you! :)
ReplyDeleteVery good example..
ReplyDeleteTerrific.I like the way u explained.thank u so much......
ReplyDeletethanks a lot for this tutorial. it was very helpful
ReplyDeleteThank you very much, It was really helpful, thanks for your time
ReplyDeleteNicely framed example. good job
ReplyDeletehey pls give short n simplest small prg which can be copy n implemented....
ReplyDeleteIts really helpfull
ReplyDeletereally good tutorial, thanks.
ReplyDeletevery nice tutorial... easy to understand the content..
ReplyDeletethanks
Velu
So clean; but I have a question for you. Since Comparators would be added for each field and newer fields, I was kind of thinking if we can come up with Generic Comparator, like one for Employee, another for Car. I can think of capturing field name into the comparator, using reflection build that getter method, and it should work I believe.
ReplyDeletethanks
ReplyDeleteregards gaurav g.
Wow, thanks a lot for clearing this up, you saved me hours of time.
ReplyDeletewhy equals() should be override in the context of Comparator/Comparable?? please send me the details discussion.
ReplyDeleteIt's really Good
ReplyDeleteI don't understand the consistency between compare(),compareTo(), and equals().
ReplyDeleteGood article.
ReplyDeletethanks...simple bt helpful
ReplyDeleteGood example, clearly explained.
ReplyDeletenice one. Able to clearly understand the concept.
ReplyDeleteWe are using Java 6 and in our case employee name may be alphanumeric... after sorting names the sorted would be like this e.g. 120,180,200,60,Ashok,Bindu.
ReplyDeleteThe desired order cann be 60,120,180...
How can i use comparator in my application..
Very nicely explained :):)Thanks
ReplyDeleteThank you very helpful!
ReplyDeleteThis really helps me a lot, thank you!!!
ReplyDeleteThis is a great tutorial. Thank You!
ReplyDeleteHi...This is nice blog..thank you for this information..It helped me...+1ed it.
ReplyDelete@Ravi Thanks
ReplyDeleteEmployee class/bean is written twice and it has the different code, which one is supposed to be used for this or else how the packaginge need to be done for running the example, pl guide
ReplyDeleteAnil
nice and short tutorial, cleared all my doubts
ReplyDeleteExcellent demo.
ReplyDeleteGreat Job done. :)
ReplyDeleteKeep posting more articles.!
if I want to sort empname basis then its working.if empname are same then sorting it according to designation both empname and designation fields are string.plz answer.
ReplyDeleteI have menu order as string with levels separated with dot (for instance it will be like 1.2.1 and 1.2.2). This works fine with a sql order by when the last numbers are upto 9 but with 10 it comes as first. After i read ur article i was able to crack it.
ReplyDeleteThanks
Thanks a lot! very informative and precise! from Sri lanka :)
ReplyDeleteWonderfully You have given your Explanation.Excellent
ReplyDeleteVery nice explanation. Good job...
ReplyDeleteSuper... lolved It..:)
ReplyDeleteWell done. This is a brilliant tutorial. So simply explains the differences between the comparable and comparator interfaces. The comparable example is superb for comparing string and integral based attributes for a custom class. It's very simple to apply this example. Oh yeah, the Comparator explanation and example is quintessential as well. Keep up the great work. Fantastic stuff. These things are extremely simple to understand, but it all goes down to how well it is explained.
ReplyDelete@134: Thanks a lot for your encouraging comment. Really appreciate it.
ReplyDeleteHi..
ReplyDeleteQuestion:In List have no.of obj's so my requirement is in List can remove one or more objs without using any loop and Iterator ? so what is the conclusion..?
if any is know the answer send me to my mail plz.....(yellappa313@gmail.com)
Really nice article..so simple yet very informative.
ReplyDeleteHi..
ReplyDeleteQuestion:How can you remove duplicate element from string?
Plz send me this Q's answer. My mail(mca.snayak@gmail.com)
Thank you! Now I know the difference
ReplyDeleteThanks Nice One
ReplyDeleteThank you for your explain...
ReplyDeletethanks, your post helped me a lot.
ReplyDeleteVery good article, i can say best one to understand comparable and comparator
ReplyDeleteHow to compare list objects two fields separetly i.e 1.name,branch 2.marks,name can any body have idea about this?i tried this but no use i cant override compareTo() method
ReplyDeleteThanks for this article, very easy to understand.
ReplyDeleteThank you for another essential article. Where else could anyone get that kind of information in such a complete way of writing? I have a presentation incoming week, and I am on the lookout for such information.
ReplyDeleteThanks for this article, this is really very easy to understand...
ReplyDeleteThanks a lot. I was very much confused with two concepts when to use what.Amazing!!!
ReplyDeleteNice explanation.....thanks a lot
ReplyDeleteThank you Kamal! Great explanation and example :)
ReplyDeleteit is very use ful me
ReplyDeletethanks you
Hi,
ReplyDeleteI understand the code wise approach but i have a doubt, you showed the Comparator also can sort by ID , then Why should we go for Comparable when we can achieve the same thing in the Comparator??
First of all i would like to say thanks for the wonderful explanation, I have a Doubt that you have showed that Comparator can do the work which Comparable can do(Ex: Your ID sort example can achievable in both), then Why we should go for Comparable when Comparator can do the same work? Why we use Comparable when all the things available in Comparator??
ReplyDeleteThank You.
Very clear and useful, thank you.
ReplyDeleteExcellent Blog on Comparable and Comparator
ReplyDelete@Naveen Shriyan - Comparable is used to compare the object itself with others, but there can be only one way of comparing when we use Camparable. However, if we need to compare the objects in different ways, the Comparator is required. For example, let's say we need to compare Employee objects based on different attributes on different scenarios; by empId at some scenarios, but by name at other scenarios. This results in the requirement of Comparator.
ReplyDelete