Java Sorting: Comparator vs Comparable Tutorial - Digizol6

Post Top Ad

Responsive Ads Here

Post Top Ad

Responsive Ads Here

Thursday, July 10, 2008

Java Sorting: Comparator vs Comparable Tutorial

Java Comparators and Comparables? What are they? How do we use them? This is a question we received from one of our readers. This article will discuss the java.util.Comparator and java.lang.Comparable in details with a set of sample codes for further clarifications.

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.
  1. positive – this object is greater than o1
  2. zero – this object equals to o1
  3. negative – this object is less than o1
java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
  1. positive – o1 is greater than o2
  2. zero – o1 equals to o2
  3. 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.
The above explained Employee example is a good candidate for explaining these two concepts. First we’ll write a simple Java bean to represent the Employee.
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
}
Next we’ll create a list of Employees for using in different sorting requirements. Employees are added to a List without any specific order in the following class.
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 ;
}
// ….
}
The new compareTo() method does the trick of implementing the natural ordering of the instances. So if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens according to the ordering done inside this method.

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());
}
}
}
Run the above class and examine the output. It will be as follows. As you can see, the list is sorted correctly using the employee id. As empId is an int value, the employee instances are ordered so that the int values ordered from 1 to 8.
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());
}
}
Watch out: Here, String class’s compareTo() method is used in comparing the name fields (which are Strings).

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());
}
}
}
Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. You’ll see that these are sorted alphabetically.
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.
  1. Sort employees using name, age, empId in this order (ie: when names are equal, try age and then next empId)
  2. Explore how & why equals() method and compare()/compareTo() methods must be consistence.
If you have any issues on these concepts; please add those in the comments section and we’ll get back to you.

Related Articles

152 comments:

  1. You should also try to handle null values.

    When dealing with comparable and comparator NPE is near far.

    ReplyDelete
    Replies

    1. True, 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.

      Delete
  2. And just to complete the example, a manually defined comparator:

    byNameLength = { a, b -> a.name.size() <=> b.name.size() } as Comparator
    pretty employees.sort(byNameLength)

    ReplyDelete
  3. this is good just what I looked for.

    cheers
    Nimch

    ReplyDelete
  4. The context in which comparable or comparator should be used is pretty clear, good tutorial

    ReplyDelete
  5. Exactly what I was looking for to get ready for exam
    Thank you very much

    ReplyDelete
  6. This tutorial is short, concise and crystal clear.
    I'm a undergraduate student learning Java and this helped me set some things I didn't understand straight.
    Thanks !

    ReplyDelete
  7. Nice one. Very helpful...

    ReplyDelete
  8. This is very helpful.

    ReplyDelete
  9. Good example.
    But 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

    ReplyDelete
  10. 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

    I'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&gt{
    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.

    ReplyDelete
  11. return o1.getEmpId().compareTo(o2.getEmpId()); in class EmpSortByEmpId doesn't compile.
    Solution : compare Strings !
    return String.valueOf(o1.getEmpId()).compareTo(String.valueOf(o2.getEmpId()));

    ReplyDelete
  12. Real good thanks! Im getting ready for exam and this was so much clearer than the PDF we was handen. Cheers

    ReplyDelete
  13. Typo above:
    negative – o1 is less than o1

    should be
    negative – o1 is less than o2

    ReplyDelete
  14. I'd like to add my thanks as well.

    Your examples were very concise and clear. They helped me actually implement Comparator as opposed to just understanding the theory.

    ReplyDelete
  15. Thanks, Really a good tutorial.

    ReplyDelete
  16. Thanks, Its really good artical to understand and well explained.

    ReplyDelete
  17. it was very usefull....thanks a lot

    ReplyDelete
  18. Good one was very useful!

    appreciate ur effort !

    ReplyDelete
  19. very nice!
    thank you!

    ReplyDelete
  20. very nice and clean!
    Thank You very much.

    ReplyDelete
  21. it very clear thank u very much

    ReplyDelete
  22. Good tutorial ,
    However 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

    ReplyDelete
  23. this really helped

    ReplyDelete
  24. Nice one !!! It would be helpful to everyone

    ReplyDelete
  25. This was the best article. Very, very helpful, nice and clean.

    ReplyDelete
  26. Excellent explanation, thanks much.

    Don

    ReplyDelete
  27. easy, concise, simple and an accurate example. Thanks Kamal

    ReplyDelete
  28. He has written a very good article . Instead of pointing out mistakes , appreciate his efforts & provide better suggestions. Great Job

    ReplyDelete
  29. Thanks a lot. Very useful tutorial. Vladimir

    ReplyDelete
  30. Very nice,easily understandable,
    and please give the why we have to override hashcode() method.

    ReplyDelete
  31. To the point and precise. Great work!!

    ReplyDelete
  32. This 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.

    Thank you and keep the tutorials coming!

    ReplyDelete
  33. 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;

    ReplyDelete
  34. thanks for a clean tutorial. I get it now !

    -Omaha, Nebraska (USA)

    ReplyDelete
  35. Is there any way to include more than one method in a single class, rather than creating single compare method in one class

    ReplyDelete
  36. nice explaination! Just one correction - Comparator interface is under java.util package and not under java.lang

    ReplyDelete
  37. Thank 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[]»).

    A well written tutorial, thanks again!

    ReplyDelete
  38. Good example............. Yeah I got the point.. Thank you very much :) cheers

    ReplyDelete
  39. really nice explanation.. hats off

    ReplyDelete
  40. good article! thanks!

    ReplyDelete
  41. veeeeeeeeeeerrrrrry helpful, thorough, and well written, thanks.

    Allasso

    ReplyDelete
  42. Thanks for your effort!It is really good!
    However ,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);
    }

    ReplyDelete
  43. // 42
    Hi fan,

    You will not need to convert int values to Strings in this example as Java5 does auto-boxing.

    ReplyDelete
  44. The explanation is super. thanks.

    ReplyDelete
  45. This really helped in my preparation about Comparable and Comparator. Well framed I book marked.

    ReplyDelete
  46. Hi,

    Very 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

    ReplyDelete
  47. Thank you for taking the time to publish this, it was very clear. The best basic tutorial on comparator I have seen!

    ReplyDelete
  48. Thank you so much ! I found what I was looking for !!
    Thanks From Paris (France).

    ReplyDelete
  49. Your post help me a lot.
    thanks from Brazil!

    ReplyDelete
  50. thank you . I from vietnamese

    ReplyDelete
  51. Thank you....Very clearly explained

    ReplyDelete
  52. Good information in precise form

    ReplyDelete
  53. Simply simple in simple terms... the basic context of both interfaces is clear

    ReplyDelete
  54. thax a lot dude...very useful tutorial....thanx again

    Prabhat

    ReplyDelete
  55. very nice... and helpful. thks biju

    ReplyDelete
  56. hi can u plz tell me why equals() and compare()methods must be consistence

    ReplyDelete
  57. Hello Kamal,
    One 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

    ReplyDelete
  58. this is very helpful tutorial. really good one

    ReplyDelete
  59. Hello Kamal,
    It 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

    ReplyDelete
  60. Very Clear. Thank You.

    ReplyDelete
  61. Thanks for your effort!It is really good!
    However ,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);
    }

    ReplyDelete
  62. very good explain nation.Really Good..Keep up the Good Work Going....

    ReplyDelete
  63. I must read your other articles. Its nice article.

    ReplyDelete
  64. Here,Collections are used for comparing the different instances but....for the same class. Why so??

    ReplyDelete
  65. Hi,

    Can u plz tell me why equals() and compare()methods must be consistence??

    Regards,
    Bibhakar.

    ReplyDelete
  66. Great, to the point post. Nice way of covering too with good examples.

    ReplyDelete
  67. Hi,

    The Comparator interface belongs to java.util.Hence please correct the article as java.util.Comparator.I think it is a typo.

    ReplyDelete
  68. This is excellence tutorial for beginners to understand the d/f b/w comparable and comparator...Excellent job

    ReplyDelete
  69. This is really great tutorial with nice example. Thanx a lot

    ReplyDelete
  70. wat's d difference between compare() and compareTo() methods

    ReplyDelete
  71. Comparator belongs to util package.....Not to lang........

    ReplyDelete
  72. Hi,
    There is a typo
    java.lang.Comparator,
    instead
    java.util.Comparator

    ReplyDelete
  73. Hi all,
    Thanks for pointing the typo in package name of java.util.Comparator interface. Now it is corrected.

    ReplyDelete
  74. 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.

    ReplyDelete
  75. I 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.

    Thanks

    ReplyDelete
  76. Very clear explanation of how comparator and comparable work with nice examples, thank you so much and keep posting more articles like this.

    ReplyDelete
  77. Excellent example.. very well explained...`

    ReplyDelete
  78. i have a problem with this code which most of it have almost same error.help me anyone

    public 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));
    }
    }

    ReplyDelete
  79. really good one.. thanks a lot

    ReplyDelete
  80. Thanks for this great explanation. I've always had trouble understanding the comparator mechanisms until now.

    ReplyDelete
  81. ('=')
    Really Superb Explaination..
    i searchd in many websites...i didnt seen this type of good explaination..
    thank u very much
    All izz well('=')

    ReplyDelete
  82. I was able to implement the same things. Thank you for this :)

    ReplyDelete
  83. Thanks alot ...Very clear and easy to understand :)

    ReplyDelete
  84. I implemented the same code... It works

    ReplyDelete
  85. One of THE best tutorial..

    ReplyDelete
  86. Nice and simple tutorial, thanks!

    ReplyDelete
  87. Awesome explanation, very useful contents.

    ReplyDelete
  88. I have one Employee Class and adding the Employee object in HashSet.
    I 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);
    }

    }

    }

    ReplyDelete
  89. 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! :)

    ReplyDelete
  90. Terrific.I like the way u explained.thank u so much......

    ReplyDelete
  91. thanks a lot for this tutorial. it was very helpful

    ReplyDelete
  92. Thank you very much, It was really helpful, thanks for your time

    ReplyDelete
  93. Nicely framed example. good job

    ReplyDelete
  94. hey pls give short n simplest small prg which can be copy n implemented....

    ReplyDelete
  95. very nice tutorial... easy to understand the content..
    thanks
    Velu

    ReplyDelete
  96. 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.

    ReplyDelete
  97. thanks
    regards gaurav g.

    ReplyDelete
  98. Wow, thanks a lot for clearing this up, you saved me hours of time.

    ReplyDelete
  99. why equals() should be override in the context of Comparator/Comparable?? please send me the details discussion.

    ReplyDelete
  100. It's really Good

    ReplyDelete
  101. I don't understand the consistency between compare(),compareTo(), and equals().

    ReplyDelete
  102. thanks...simple bt helpful

    ReplyDelete
  103. Good example, clearly explained.

    ReplyDelete
  104. nice one. Able to clearly understand the concept.

    ReplyDelete
  105. We 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.
    The desired order cann be 60,120,180...
    How can i use comparator in my application..

    ReplyDelete
  106. Very nicely explained :):)Thanks

    ReplyDelete
  107. Thank you very helpful!

    ReplyDelete
  108. This really helps me a lot, thank you!!!

    ReplyDelete
  109. This is a great tutorial. Thank You!

    ReplyDelete
  110. Hi...This is nice blog..thank you for this information..It helped me...+1ed it.

    ReplyDelete
  111. Employee 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

    Anil

    ReplyDelete
  112. nice and short tutorial, cleared all my doubts

    ReplyDelete
  113. Great Job done. :)
    Keep posting more articles.!

    ReplyDelete
  114. 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.

    ReplyDelete
  115. I 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.

    Thanks

    ReplyDelete
  116. Thanks a lot! very informative and precise! from Sri lanka :)

    ReplyDelete
  117. Wonderfully You have given your Explanation.Excellent

    ReplyDelete
  118. Very nice explanation. Good job...

    ReplyDelete
  119. Super... lolved It..:)

    ReplyDelete
  120. Well 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
  121. @134: Thanks a lot for your encouraging comment. Really appreciate it.

    ReplyDelete
  122. Hi..

    Question: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)

    ReplyDelete
  123. Really nice article..so simple yet very informative.

    ReplyDelete
  124. Hi..
    Question:How can you remove duplicate element from string?
    Plz send me this Q's answer. My mail(mca.snayak@gmail.com)

    ReplyDelete
  125. Thank you! Now I know the difference

    ReplyDelete
  126. Thank you for your explain...

    ReplyDelete
  127. thanks, your post helped me a lot.

    ReplyDelete
  128. Very good article, i can say best one to understand comparable and comparator

    ReplyDelete
  129. How 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

    ReplyDelete
  130. Thanks for this article, very easy to understand.

    ReplyDelete
  131. Thank 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.

    ReplyDelete
  132. Thanks for this article, this is really very easy to understand...

    ReplyDelete
  133. Thanks a lot. I was very much confused with two concepts when to use what.Amazing!!!

    ReplyDelete
  134. Nice explanation.....thanks a lot

    ReplyDelete
  135. Thank you Kamal! Great explanation and example :)

    ReplyDelete
  136. it is very use ful me

    thanks you

    ReplyDelete
  137. Hi,
    I 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??

    ReplyDelete
  138. 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??

    Thank You.

    ReplyDelete
  139. Excellent Blog on Comparable and Comparator

    ReplyDelete
  140. @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

Post Top Ad

Responsive Ads Here