Home Tutorials News Software Online Money Web Designing

Embed Size (px)

Citation preview

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    1/34

    HomeTutorialsNewsSoftwareOnline MoneyWeb Designing| Contact | Facebook| Twitter

    Java Sorting: Comparator

    vs Comparable Tutorial

    Article By Kamal Mettananda on July 10, 2008

    Java Comparators and Comparables? What arethey? How do we use them? This is a question wereceived from one of our readers. This article willdiscuss the java.util.Comparator andava.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 theseconcepts; Java objects can besorted according to a predefined order.

    Two of these concepts can be explained as follows.

    MOST POPULAR ARTICLES

    UnsupportedClassVersionError

    Java Sorting: Comparatorvs Comparable Tutorial

    Margin Vs Padding - CSSProperties

    Add css styles for gwtwidgets

    Web Services with ApacheAxis 1.4 Tutorial

    ARCHIVESSelect Month:ABOUT AUTHOR

    Kamal Mettananadais a Software Architect, JavaExplorer and Blogger. Digizolconsists of computer relatedarticles, tutorials, tips and otherinformation.LATEST ARTICLES

    1. Create/Restore InternetExplorer desktop shortcut2. Change Apache Tomcat port

    8080 to 80 or another po...3. java.lang.UnsupportedClass

    VersionError: Bad versio...4. java.lang.SecurityException:

    Blocked attempt to ac...5. Axis Web services Problem:

    No compiler found in yo...6. Six sixes in one over in

    Twenty20 Cricket - World...

    http://www.digizol.org/http://www.digizol.org/search/label/Javahttp://www.digizol.org/search/label/Javahttp://www.digizol.org/search/label/Newshttp://www.digizol.org/search/label/Newshttp://www.digizol.org/search/label/Softwarehttp://www.digizol.org/search/label/Softwarehttp://www.digizol.org/search/label/Earn%20Onlinehttp://www.digizol.org/search/label/Earn%20Onlinehttp://www.digizol.org/search/label/Web%20Designhttp://www.digizol.org/search/label/Web%20Designhttp://www.digizol.org/search/label/Web%20Designmailto:admin%28at%29digizol%28dot%29orghttp://www.facebook.com/digizolhttp://twitter.com/digizolhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2008/03/toolsjar-runtimeexception-no-compiler.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2006/12/margin-vs-padding-css-properties.htmlhttp://www.digizol.org/2006/12/margin-vs-padding-css-properties.htmlhttp://www.digizol.org/2006/12/margin-vs-padding-css-properties.htmlhttp://www.digizol.org/2006/12/margin-vs-padding-css-properties.htmlhttp://www.digizol.org/2007/08/add-css-style-for-gwt-widgets.htmlhttp://www.digizol.org/2007/08/add-css-style-for-gwt-widgets.htmlhttp://www.digizol.org/2007/08/add-css-style-for-gwt-widgets.htmlhttp://www.digizol.org/2007/08/add-css-style-for-gwt-widgets.htmlhttp://www.digizol.org/2008/07/web-service-axis-tutorial-client-server.htmlhttp://www.digizol.org/2008/07/web-service-axis-tutorial-client-server.htmlhttp://www.digizol.org/2008/07/web-service-axis-tutorial-client-server.htmlhttp://www.digizol.org/2008/07/web-service-axis-tutorial-client-server.htmlhttp://www.digizol.org/2008/06/internet-explorer-shortcut-create.htmlhttp://www.digizol.org/2008/06/internet-explorer-shortcut-create.htmlhttp://www.digizol.org/2008/06/internet-explorer-shortcut-create.htmlhttp://www.digizol.org/2008/06/internet-explorer-shortcut-create.htmlhttp://www.digizol.org/2008/06/tomcat-how-to-change-port-8080.htmlhttp://www.digizol.org/2008/06/tomcat-how-to-change-port-8080.htmlhttp://www.digizol.org/2008/06/tomcat-how-to-change-port-8080.htmlhttp://www.digizol.org/2008/06/tomcat-how-to-change-port-8080.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/04/gwt-exception-dispatching-incoming-rpc.htmlhttp://www.digizol.org/2008/04/gwt-exception-dispatching-incoming-rpc.htmlhttp://www.digizol.org/2008/04/gwt-exception-dispatching-incoming-rpc.htmlhttp://www.digizol.org/2008/04/gwt-exception-dispatching-incoming-rpc.htmlhttp://www.digizol.org/2008/03/toolsjar-runtimeexception-no-compiler.htmlhttp://www.digizol.org/2008/03/toolsjar-runtimeexception-no-compiler.htmlhttp://www.digizol.org/2008/03/toolsjar-runtimeexception-no-compiler.htmlhttp://www.digizol.org/2008/03/toolsjar-runtimeexception-no-compiler.htmlhttp://www.digizol.org/2007/09/six-sixes-twenty20-cricket-world-record.htmlhttp://www.digizol.org/2007/09/six-sixes-twenty20-cricket-world-record.htmlhttp://www.digizol.org/2007/09/six-sixes-twenty20-cricket-world-record.htmlhttp://www.digizol.org/2007/09/six-sixes-twenty20-cricket-world-record.htmlhttp://www.digizol.org/2007/09/six-sixes-twenty20-cricket-world-record.htmlhttp://feeds2.feedburner.com/lkamal/rsshttp://www.digizol.org/http://feeds2.feedburner.com/lkamal/rsshttp://www.digizol.org/http://feeds2.feedburner.com/lkamal/rsshttp://www.digizol.org/http://feeds2.feedburner.com/lkamal/rsshttp://www.digizol.org/http://www.digizol.org/2007/09/six-sixes-twenty20-cricket-world-record.htmlhttp://www.digizol.org/2007/09/six-sixes-twenty20-cricket-world-record.htmlhttp://www.digizol.org/2007/09/six-sixes-twenty20-cricket-world-record.htmlhttp://www.digizol.org/2008/03/toolsjar-runtimeexception-no-compiler.htmlhttp://www.digizol.org/2008/03/toolsjar-runtimeexception-no-compiler.htmlhttp://www.digizol.org/2008/04/gwt-exception-dispatching-incoming-rpc.htmlhttp://www.digizol.org/2008/04/gwt-exception-dispatching-incoming-rpc.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/06/tomcat-how-to-change-port-8080.htmlhttp://www.digizol.org/2008/06/tomcat-how-to-change-port-8080.htmlhttp://www.digizol.org/2008/06/internet-explorer-shortcut-create.htmlhttp://www.digizol.org/2008/06/internet-explorer-shortcut-create.htmlhttp://www.digizol.org/2008/07/web-service-axis-tutorial-client-server.htmlhttp://www.digizol.org/2008/07/web-service-axis-tutorial-client-server.htmlhttp://www.digizol.org/2007/08/add-css-style-for-gwt-widgets.htmlhttp://www.digizol.org/2007/08/add-css-style-for-gwt-widgets.htmlhttp://www.digizol.org/2006/12/margin-vs-padding-css-properties.htmlhttp://www.digizol.org/2006/12/margin-vs-padding-css-properties.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/04/javalangunsupportedclassversionerror.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://twitter.com/digizolhttp://www.facebook.com/digizolmailto:admin%28at%29digizol%28dot%29orghttp://www.digizol.org/search/label/Web%20Designhttp://www.digizol.org/search/label/Earn%20Onlinehttp://www.digizol.org/search/label/Softwarehttp://www.digizol.org/search/label/Newshttp://www.digizol.org/search/label/Javahttp://www.digizol.org/
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    2/34

    Comparable

    A comparable object is capable of comparing itself with

    another object. The class itself must implements theava.lang.Comparable interface in order to be able tocompare its instances.

    Comparator

    A comparator object is capable of comparing twodifferent objects. The class is not comparing itsinstances, but some other classs instances. This

    comparator class must implement theava.util.Comparator interface.

    Do we need to compare objects?

    The simplest answer is yes. Whenthere is a list of objects, ordering these objects intodifferent orders becomes a must in some situations. Forexample; think of displaying a list of employee objects ina web page. Generally employees may be displayed bysorting them using the employee id. Also there will berequirements to sort them according to the name or ageas well. In these situations both these (above defined)concepts will become handy.

    How to use these?

    There are two interfaces in Java to support theseconcepts, and each of these has one method to beimplemented by user.

    Those are;

    ava.lang.Comparable: int compareTo(Object o1)This method compares this object with o1 object.Returned int value has the following meanings.

    1. positivethis object is greater than o12. zerothis object equals to o13. negativethis object is less than o1

    ava.util.Comparator: int compare(Object o1,

    7. [Java Tips] Add Array into aList and convert a Li...

    8. QuickTime security issuefixed with Firefox 2.0.0....

    9. svnadmin create a newempty project repository in...

    10.Call javascript in body tagon different events

    Fan PageBlog Roll

    Just Another Tech Blog OnGWT Tracking News on

    GWT

    http://www.digizol.org/2007/09/java-array-list-array-convert-insert.htmlhttp://www.digizol.org/2007/09/java-array-list-array-convert-insert.htmlhttp://www.digizol.org/2007/09/java-array-list-array-convert-insert.htmlhttp://www.digizol.org/2007/09/java-array-list-array-convert-insert.htmlhttp://www.digizol.org/2007/09/firefox-2007-quicktime-issue.htmlhttp://www.digizol.org/2007/09/firefox-2007-quicktime-issue.htmlhttp://www.digizol.org/2007/09/firefox-2007-quicktime-issue.htmlhttp://www.digizol.org/2007/09/firefox-2007-quicktime-issue.htmlhttp://www.digizol.org/2007/09/svnadmin-subversion-create-repository.htmlhttp://www.digizol.org/2007/09/svnadmin-subversion-create-repository.htmlhttp://www.digizol.org/2007/09/svnadmin-subversion-create-repository.htmlhttp://www.digizol.org/2007/09/svnadmin-subversion-create-repository.htmlhttp://www.digizol.org/2007/09/svnadmin-subversion-create-repository.htmlhttp://www.digizol.org/2007/09/call-javascript-in-body-tag-on-events.htmlhttp://www.digizol.org/2007/09/call-javascript-in-body-tag-on-events.htmlhttp://www.digizol.org/2007/09/call-javascript-in-body-tag-on-events.htmlhttp://www.digizol.org/2007/09/call-javascript-in-body-tag-on-events.htmlhttp://www.justanothertechblog.blogspot.com/http://www.ongwt.com/http://www.ongwt.com/http://www.ongwt.com/http://www.ongwt.com/http://www.ongwt.com/http://www.ongwt.com/http://www.justanothertechblog.blogspot.com/http://www.digizol.org/2007/09/call-javascript-in-body-tag-on-events.htmlhttp://www.digizol.org/2007/09/call-javascript-in-body-tag-on-events.htmlhttp://www.digizol.org/2007/09/svnadmin-subversion-create-repository.htmlhttp://www.digizol.org/2007/09/svnadmin-subversion-create-repository.htmlhttp://www.digizol.org/2007/09/svnadmin-subversion-create-repository.htmlhttp://www.digizol.org/2007/09/firefox-2007-quicktime-issue.htmlhttp://www.digizol.org/2007/09/firefox-2007-quicktime-issue.htmlhttp://www.digizol.org/2007/09/java-array-list-array-convert-insert.htmlhttp://www.digizol.org/2007/09/java-array-list-array-convert-insert.html
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    3/34

    Objecto2)This method compares o1 and o2 objects. Returned intvalue has the following meanings.

    1. positiveo1 is greater than o22. zeroo1 equals to o23. negativeo1 is less than o2

    ava.util.Collections.sort(List) andava.util.Arrays.sort(Object[]) methods can be used to

    sort using natural ordering of objects.ava.util.Collections.sort(List, Comparator) andava.util.Arrays.sort(Object[], Comparator) methods

    can be used if a Comparator is available for comparison.

    The above explained Employee example is a goodcandidate for explaining these two concepts. First well

    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

    }

    ext well create a list of Employees for using in

    different sorting requirements. Employees are added to aList without any specific order in the following class.

    import java.util.*;

    public class Util {

    public static List getEmployees() {

    List col = new

    ArrayList();

    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;

    }

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    4/34

    }

    Sorting in natural ordering

    Employees natural ordering would be done according to

    the employee id. For that, above Employee class must bealtered to add the comparing ability as follows.

    public class Employee implements

    Comparable {

    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 ofimplementing the natural ordering of the instances. So if

    a collection of Employee objects is sorted usingCollections.sort(List) method; sorting happens accordingto the ordering done inside this method.

    Well write a class to test this natural ordering

    mechanism. Following class use theCollections.sort(List) method to sort the given list innatural 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

    list) {

    System.out.println("EmpId\tName\tAge");

    for (Employee e: list) {

    System.out.println(e.getEmpId() + "\t" +

    e.getName() + "\t" + e.getAge());

    }}

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    5/34

    }

    Run the above class and examine the output. It will be asfollows. As you can see, the list is sorted correctly usingthe employee id. As empId is an int value, the employee

    instances are ordered so that the int values ordered from1 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,well have to change the Employee classs compareTo()method to use those fields. But then well loose this

    empId based sorting mechanism. This is not a goodalternative if we need to sort using different fields atdifferent occasions. But no need to worry; Comparator isthere to save us.

    By writing a class that implements theava.util.Comparator interface, you can sort Employees

    using any field as you wish even without touching theEmployee class itself; Employee class does not need toimplement java.lang.Comparable or java.util.Comparatorinterface.

    Sorting by name field

    Following EmpSortByName class is used to sortEmployee instances according to the name field. In thisclass, inside the compare() method sorting mechanism isimplemented. In compare() method we get twoEmployee instances and we have to return which objectis greater.

    public class EmpSortByName implements

    Comparator{

    public int compare(Employee o1, Employee o2) {

    return o1.getName().compareTo(o2.getName());

    }

    }

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    6/34

    Watch out:Here, String classs compareTo() method isused in comparing the name fields (which are Strings).

    Now to test this sorting mechanism, you must use the

    Collections.sort(List, Comparator) method instead ofCollections.sort(List) method. Now change theTestEmployeeSort class as follows. See how theEmpSortByName 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

    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 theemployees are sorted correctly by the name String field.Youll 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 usingComparable) can be implemented using Comparator;following classdoes that.

    public class EmpSortByEmpId implementsComparator{

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    7/34

    public int compare(Employee o1, Employee o2) {

    return o1.getEmpId() - o2.getEmpId();

    }

    }

    Explore further

    Do not stop here. Work on the followings by yourselvesand sharpen knowledge on these concepts.

    1. Sort employees using name, age, empId in thisorder (ie: when names are equal, try age and thennext empId)

    2. Explore how & why equals() method andcompare()/compareTo() methods must beconsistence.

    If you have any issues on these concepts; please addthose in the comments section and well get back to you.

    Labels: Java, Tech, Tutorial

    Search more articles

    Search Digizol ...

    What's Next?

    ShareThis

    Post a Comment

    We appreciate your opinions, suggestions and criticism.

    1. Thierry (July 10, 2008 7:31 PM)You should also try to handle null values.

    When dealing with comparable and comparatorNPE is near far.

    2. Kamal Mettananda (July 11, 2008 9:23 AM)True, there will be situations where you caughtup with NPE. But I don't think this responsibility

    http://www.digizol.org/search/label/Javahttp://www.digizol.org/search/label/Techhttp://www.digizol.org/search/label/Tutorialhttp://www.jroller.com/thierry/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2136219364882690239http://www.blogger.com/profile/03241660835422874258http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8346315733374702788http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8346315733374702788http://www.blogger.com/profile/03241660835422874258http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2136219364882690239http://www.jroller.com/thierry/http://www.digizol.org/search/label/Tutorialhttp://www.digizol.org/search/label/Techhttp://www.digizol.org/search/label/Java
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    8/34

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    9/34

    this is good just what I looked for.

    cheersNimch

    6. Anonymous (November 01, 2008 3:32 AM)The context in which comparable or comparatorshould be used is pretty clear, good tutorial

    7. Anonymous (November 10, 2008 5:29 AM)Exactly what I was looking for to get ready forexamThank you very much

    8. Anonymous (November 30, 2008 6:39 PM)This tutorial is short, concise and crystal clear.I'm a undergraduate student learning Java andthis helped me set some things I didn't understandstraight.Thanks !

    9. Anonymous (December 02, 2008 11:27 AM)Nice one. Very helpful...

    10. Anonymous (December 19, 2008 3:34 AM)This is very helpful.

    11. Anonymous (January 21, 2009 9:04 PM)Good example.But this code working just for Java 5 and higher .But for some reason I need to use Java 1.4. Nextthe same code for Java 1.4: It looks like:1. public class Employee implementsComparable{2. public int compareTo(Object o) {Employee e = new Employee();e = (Employee)o;return this.empId - e.getEmpId() ;3. public class EmpSortByName implementsComparator{public int compare(Object o1, Object o2) {

    Employee e1 = new Employee();e1 = (Employee)o1;

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6085081181207413741http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c797769753657372003http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8283455727345363107http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6477991728387301172http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5651579811345894184http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8695515003982885580http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8695515003982885580http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5651579811345894184http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6477991728387301172http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8283455727345363107http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c797769753657372003http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6085081181207413741
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    10/34

    Employee e2 = new Employee();e2 = (Employee)o2;return e1.getName().compareTo(e2.getName());

    Thanks

    Igor Chirokov

    12. Anonymous (January 23, 2009 5:39 PM)1.In this list I have multiple elements and I'mneeding to sort by 2 elements within this list: firstby binSortCode and then by itemDescr

    I've been googling and trying to get some helpbut am having problems trying to understandingcomparable vs comparator. I had usedcomparable to sort on a single element and itworked find but when trying to sort on multipleelements I'm not able to make it work.

    I have created a comparator class where I amtrying to sort first on binSortCode and then sorton itemDesc, please see the following:

    public class CommonListItemSort implementsComparator$ltCommonListItem&gt{

    2.3. //Sort common list items by bin sort code thenby item description4. 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.getIt

    emDesc());8. return diff;11. }12. }13.14. I then call this class from my servicebean asfollows:15.16. public CommonList getDetails(final StringentityCode, final String commonListName) {17. CommonList commonList =

    commonListDao.find(commonListName,entityCode);

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6814289049271329756http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6814289049271329756
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    11/34

    18.19. //Sort the items by binsortcode and then byitem description20.Collections.sort(commonList.getCommonListIte

    ms(), new CommonListItemSort());21. return commonList;22. }

    The outcome that I'm getting is that binSortCodeis in DESC order and itemDesc is in ASC orderwhere in actuality I need the list to sort first bybinSortCode ASC and then itemDesc in ASC.

    Any help or direction would be greatlyappreciated. Thanks.

    13. Anonymous (February 12, 2009 7:32 PM)returno1.getEmpId().compareTo(o2.getEmpId()); inclass EmpSortByEmpId doesn't compile.Solution : compare Strings !returnString.valueOf(o1.getEmpId()).compareTo(String.valueOf(o2.getEmpId()));

    14. Anonymous (February 19, 2009 6:28 PM)Real good thanks! Im getting ready for exam andthis was so much clearer than the PDF we washanden. Cheers

    15. Anonymous (February 25, 2009 8:55 PM)Typo above:negativeo1 is less than o1

    should benegativeo1 is less than o2

    16. Jim (March 15, 2009 12:02 PM)I'd like to add my thanks as well.

    Your examples were very concise and clear. Theyhelped me actually implement Comparator asopposed to just understanding the theory.

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7407915800617186414http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1949392989032711487http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7796593178783676382http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2202526764100030555http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2202526764100030555http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7796593178783676382http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1949392989032711487http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7407915800617186414
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    12/34

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    13/34

    26. BHARAT PATEL (July 14, 2009 3:54 PM)Nice one !!! It would be helpful to everyone

    27. Anonymous (July 16, 2009 5:13 PM)This was the best article. Very, very helpful, niceand clean.

    28. Anonymous (July 20, 2009 9:00 PM)Excellent explanation, thanks much.

    Don

    29.

    Anonymous (July 21, 2009 10:41 PM)

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

    30. Anonymous (July 26, 2009 7:42 AM)He has written a very good article . Instead ofpointing out mistakes , appreciate his efforts &provide better suggestions. Great Job

    31. Vova (July 26, 2009 3:45 PM)Thanks a lot. Very useful tutorial. Vladimir

    32. ram (July 27, 2009 4:46 PM)Very nice,easily understandable,and please give the why we have to overridehashcode() method.

    33. solitude (August 18, 2009 8:47 AM)To the point and precise. Great work!!

    34. Anonymous (September 17, 2009 9:18 PM)This tutorial was fantastic. I knew I needed to usea Comparator, but it's been a long time since Ilast did one. This information was exactly what Ineeded to get the job done and jogged my brainagain.

    http://www.blogger.com/profile/12808389933656050126http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6607309814313966736http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5326906815780425903http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3208235615800439594http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3546552426719999551http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7054165112113087423http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5745043523840061499http://www.blogger.com/profile/03507945874858703078http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3791332347671641638http://www.blogger.com/profile/13825939133662309074http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3455281560322522637http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7412580212189540325http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7412580212189540325http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3455281560322522637http://www.blogger.com/profile/13825939133662309074http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3791332347671641638http://www.blogger.com/profile/03507945874858703078http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5745043523840061499http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7054165112113087423http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3546552426719999551http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3208235615800439594http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5326906815780425903http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6607309814313966736http://www.blogger.com/profile/12808389933656050126
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    14/34

    Thank you and keep the tutorials coming!

    35. pinku (October 12, 2009 11:37 AM)you have written in definition of the Comparator

    that it belongs to java.lang.comparator but it iswrong and instead it belongs to

    java.util.comparator;

    36. Anonymous (October 18, 2009 4:57 AM)thanks for a clean tutorial. I get it now !

    -Omaha, Nebraska (USA)

    37.

    Jijo Mathew (October 25, 2009 5:08 PM)

    Is there any way to include more than one methodin a single class, rather than creating singlecompare method in one class

    38. bhushan (November 24, 2009 7:21 PM)nice explaination! Just one correction -Comparator interface is under java.util packageand not under java.lang

    39. Marios (November 29, 2009 7:00 AM)Thank you! I have been searching for hours howto sort my ArrayList and only your tutorial mademe understand what I was doing wrong (myArrayList was made of arrays, as inArrayListdouble[]).

    A well written tutorial, thanks again!

    40. Anonymous (December 10, 2009 4:06 PM)Good example............. Yeah I got the point..Thank you very much :) cheers

    41. sweetu (December 15, 2009 11:58 PM)really nice explanation.. hats off

    42. Anonymous (December 18, 2009 11:35 PM)

    http://www.blogger.com/profile/15358306626547323913http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8937606728410722867http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7073359053972231536http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8012585325149300833http://www.blogger.com/profile/10101872432786112986http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8233764074059595803http://www.andmarios.com/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5574211023022213939http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7017825745385700362http://www.blogger.com/profile/01674227501436737759http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c667985418475352682http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6973054764748495165http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6973054764748495165http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c667985418475352682http://www.blogger.com/profile/01674227501436737759http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7017825745385700362http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5574211023022213939http://www.andmarios.com/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8233764074059595803http://www.blogger.com/profile/10101872432786112986http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8012585325149300833http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7073359053972231536http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8937606728410722867http://www.blogger.com/profile/15358306626547323913
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    15/34

    good article! thanks!

    43. Anonymous (December 22, 2009 11:27 PM)veeeeeeeeeeerrrrrry helpful, thorough, and well

    written, thanks.

    Allasso

    44. fan (December 27, 2009 2:34 PM)Thanks for your effort!It is really good!However ,I found that the last part "Sorting byempId field" does not work !I have to cast the int into String first,public class EmpSortByEmpId implementsComparator{

    public int compare(Employee o1, Employee o2) {String myStringO1 =Integer.toString(o1.getEmpId());String myStringO2 =Integer.toString(o2.getEmpId());return myStringO1.compareTo(myStringO2);}

    45. Kamal Mettananda (December 29, 2009 8:44PM)// 42Hi fan,

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

    46. Anonymous (February 03, 2010 1:25 AM)The explanation is super. thanks.

    47. Anonymous (February 17, 2010 12:02 AM)This really helped in my preparation aboutComparable and Comparator. Well framed I bookmarked.

    48. Anonymous (February 20, 2010 12:56 PM)Hi,

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c103934441319786810http://www.blogger.com/profile/15903808763136044731http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1835163702620620894http://www.blogger.com/profile/03241660835422874258http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4757574512706285633http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4757574512706285633http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1443374904046268019http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1285603997985235323http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4138914303677029409http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4138914303677029409http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1285603997985235323http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1443374904046268019http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4757574512706285633http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4757574512706285633http://www.blogger.com/profile/03241660835422874258http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1835163702620620894http://www.blogger.com/profile/15903808763136044731http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c103934441319786810
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    16/34

    Very Nice article..It made me very clear abt theComparable and Comparator interface.. I hadchecked few sites..but there was no clear info asyou have provided.. Thanks

    49. -Mancini (February 25, 2010 12:08 AM)Thank you for taking the time to publish this, itwas very clear. The best basic tutorial oncomparator I have seen!

    50. Anonymous (March 01, 2010 3:41 PM)Thank you so much ! I found what I was lookingfor !!Thanks From Paris (France).

    51. Anonymous (March 24, 2010 3:28 AM)Your post help me a lot.thanks from Brazil!

    52. Anonymous (March 30, 2010 11:02 PM)thank you . I from vietnamese

    53. Anonymous (April 12, 2010 3:57 PM)Thank you....Very clearly explained

    54. Anonymous (April 14, 2010 6:32 PM)Good information in precise form

    55. Candle(April 15, 2010 12:14 AM)Thanks, it helped me.

    56. Anonymous (April 30, 2010 10:00 AM)Simply simple in simple terms... the basic contextof both interfaces is clear

    57. Asanthine (May 11, 2010 3:20 PM)hi

    58. Anonymous (May 25, 2010 6:10 PM)

    http://www.blogger.com/profile/07192224122374544530http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c829443017140897065http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6889816983060717319http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6171467559029940460http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8329630426845068175http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2745036497256754630http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6559560622314131519http://www.blogger.com/profile/03510326299173246335http://www.blogger.com/profile/03510326299173246335http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3425445391948461082http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3088103628010496791http://www.gmail.com/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2628848823902072675http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5523047328561548829http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5523047328561548829http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2628848823902072675http://www.gmail.com/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3088103628010496791http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3425445391948461082http://www.blogger.com/profile/03510326299173246335http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6559560622314131519http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2745036497256754630http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8329630426845068175http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6171467559029940460http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6889816983060717319http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c829443017140897065http://www.blogger.com/profile/07192224122374544530
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    17/34

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

    Prabhat

    59. Anonymous (May 31, 2010 8:42 PM)very nice... and helpful. thks biju

    60. Anonymous (June 01, 2010 8:08 PM)hi can u plz tell me why equals() andcompare()methods must be consistence

    61. aparajeeta (June 03, 2010 3:39 PM)Hello Kamal,One very important correction needs to be madeto this post. Comparator belongs to the java.utilpackage and not java.lang as you have mentionedin the beginning of the post. Please rectify as thisa crucial thing to be overlooked.

    regards,Aparajeeta

    62. hardeep thakur (June 09, 2010 9:51 AM)this is very helpful tutorial. really good one

    63. Anonymous (June 09, 2010 1:28 PM)Hello Kamal,It is simple and very helpful.one Imp.note I too observed that the comparatorinterface is from java.util, but is is mentioned asfrom java.lang in the beginning (How to usethese? section).

    Thank you.Santhosh

    64. Anonymous (June 13, 2010 5:55 AM)Very Clear. Thank You.

    65. Anonymous (June 17, 2010 9:33 PM)Thanks for your effort!It is really good!However ,I found that the last part "Sorting by

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2245746700295610610http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3711465267014263217http://technicknacks.blogspot.com/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4440436158044723546http://www.blogger.com/profile/04684240861921791304http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8721894364610083023http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6882924653907804371http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1605444482955217180http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5842135111957313060http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5842135111957313060http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1605444482955217180http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6882924653907804371http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8721894364610083023http://www.blogger.com/profile/04684240861921791304http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4440436158044723546http://technicknacks.blogspot.com/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3711465267014263217http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2245746700295610610
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    18/34

    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. Imean int to String.compateTo() method compares only Strings only

    public class EmpSortByEmpId implementsComparator{

    public int compare(Employee o1, Employee o2) {String myStringO1 =Integer.toString(o1.getEmpId());String myStringO2 =Integer.toString(o2.getEmpId());return myStringO1.compareTo(myStringO2);}

    66. Anonymous (June 21, 2010 12:14 AM)very good explain nation.Really Good..Keep upthe Good Work Going....

    67. My Errors (July 05, 2010 2:48 PM)I must read your other articles. Its nice article.

    68. Anonymous (July 06, 2010 12:18 PM)Here,Collections are used for comparing thedifferent instances but....for the same class. Whyso??

    69. Anonymous (July 06, 2010 12:20 PM)Hi,

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

    Regards,Bibhakar.

    70. Hiten (July 12, 2010 11:54 PM)Great, to the point post. Nice way of covering toowith good examples.

    71. Anonymous (August 06, 2010 10:25 PM)Hi,

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3666233435363049995http://www.blogger.com/profile/14062740169701183631http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4633761465346795216http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4531646415228022297http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6280324414413170578http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c894471640984549867http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4692654154387294472http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4692654154387294472http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c894471640984549867http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6280324414413170578http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4531646415228022297http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4633761465346795216http://www.blogger.com/profile/14062740169701183631http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c3666233435363049995
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    19/34

    The Comparator interface belongs to

    java.util.Hence please correct the article asjava.util.Comparator.I think it is a typo.

    72. Anonymous (August 13, 2010 4:40 PM)This is excellence tutorial for beginners tounderstand the d/f b/w comparable andcomparator...Excellent job

    73. kamal (August 31, 2010 1:54 PM)This is really great tutorial with nice example.Thanx a lot

    74. Anonymous (September 06, 2010 3:26 PM)wat's d difference between compare() andcompareTo() methods

    75. Anonymous (September 09, 2010 11:01 AM)Comparator belongs to util package.....Not tolang........

    76. Anonymous (September 09, 2010 3:59 PM)Hi,There is a typo

    java.lang.Comparator,instead

    java.util.Comparator

    77. Kamal Mettananda (September 19, 2010 8:04PM)

    Hi all,Thanks for pointing the typo in package name of

    java.util.Comparator interface. Now it iscorrected.

    78. Anonymous (September 23, 2010 11:27 AM)Thank you so much for the explanation andexamples, its really helps me. Only that..i goterror..java.lang.ClassCastException:

    java.lang.String cannot be cast to..when i tried tomake sorting with integer by following example

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2872657890210856212http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8521454651639112334http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1859099363347215071http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4283707674182399168http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8454414283760259895http://www.blogger.com/profile/03241660835422874258http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4612209146597861920http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4612209146597861920http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2983867582689905355http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2983867582689905355http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4612209146597861920http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4612209146597861920http://www.blogger.com/profile/03241660835422874258http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8454414283760259895http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4283707674182399168http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1859099363347215071http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8521454651639112334http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2872657890210856212
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    20/34

    Sorting by empId field. Can anybody help me?Thank you.

    79. ocpjp (October 03, 2010 2:27 AM)I have menu order as string with levels separatedwith dot (for instance it will be like 1.2.1 and1.2.2). This works fine with a sql order by whenthe last numbers are upto 9 but with 10 it comesas first. After i read ur article i was able to crackit.

    Thanks

    80. mrudula (October 04, 2010 6:22 PM)Very clear explanation of how comparator andcomparable work with nice examples, thank youso much and keep posting more articles like this.

    81. Anonymous (October 07, 2010 1:28 AM)Excellent example.. very well explained...`

    82. elmy onetwo (October 08, 2010 8:57 PM)i have a problem with this code which most of ithave almost same error.help me anyone

    public interface Comparable{public int compareTo(Object o);

    }public class BinarySearch1{

    public static final boolean contains(Comparableitem, Comparable[] array, int n){

    int low = 0;int high = n - 1;while (low 0){low = mid + 1;}else {

    http://ocpjp.com/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7418590682703730138http://www.blogger.com/profile/10037605990142802183http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c44704603367398057http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c120997364407834248http://www.blogger.com/profile/14965296655158553021http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6813551176699883167http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6813551176699883167http://www.blogger.com/profile/14965296655158553021http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c120997364407834248http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c44704603367398057http://www.blogger.com/profile/10037605990142802183http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7418590682703730138http://ocpjp.com/
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    21/34

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

    83. Anonymous (October 15, 2010 9:16 AM)really good one.. thanks a lot

    84. Anonymous (October 24, 2010 1:35 PM)Thanks for this great explanation. I've always hadtrouble understanding the comparator

    mechanisms until now.

    85. Anonymous (October 28, 2010 7:04 PM)('=')Really Superb Explaination..i searchd in many websites...i didnt seen this typeof good explaination..thank u very muchAll izz well('=')

    86. Anonymous (November 12, 2010 9:47 PM)I was able to implement the same things. Thankyou for this :)

    87. Anonymous (November 15, 2010 11:26 PM)Thanks alot ...Very clear and easy to understand:)

    88.

    Anonymous (November 15, 2010 11:27 PM)

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1308923173954302422http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6914183574915203315http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6008145643115527101http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4696167231822666341http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6255701635569776318http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c551872341999227247http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c551872341999227247http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6255701635569776318http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4696167231822666341http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6008145643115527101http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6914183574915203315http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1308923173954302422
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    22/34

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    23/34

    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, Employeeemp2){return((emp1.getName()).compareTo(emp2.getName())

    );}}

    class EmpsortByID implements Comparator{public int compare(Employee emp1, Employeeemp2){return((emp1.getEmpID()).compareTo(emp2.getEmpID()));}

    }

    class EmpsortBySalary implements Comparator{public int compare(Employee emp1, Employeeemp2){return emp1.getSalary()- emp2.getSalary();}}

    public class EmployeeHashSet{

    public static void main(String []asgs){

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    24/34

    Set empset = new HashSet();

    empset.add(newEmployee("emp1011","Andrew", 30000));empset.add(new Employee("emp1021","Stuart",

    20000));empset.add(newEmployee("emp5043","Symond", 40000));empset.add(new Employee("emp1010","Rob",30700));empset.add(new Employee("emp1020","Bill",20900));empset.add(newEmployee("emp5053","Bill",41000));

    TreeSet setlist=new TreeSet(empset);Collections.sort(new ArrayList(setlist),newEmpsortByName());

    Iterator iterator = setlist.iterator();System.out.println("\\Employee names in sortedorder::");

    while(iterator.hasNext()){Employee emp= (Employee)iterator.next();System.out.println(emp.getName());

    System.out.println(emp);}

    }

    }

    94. Geir (January 05, 2011 1:53 AM)Ahh, this tutorial was so crystal clear, nice andsmall compared to the dreadfully long and

    complex code examples in my thick java book.Thank you! :)

    95. Rakesh (January 11, 2011 4:28 PM)Very good example..

    96. Anonymous (January 18, 2011 5:24 AM)Terrific.I like the way u explained.thank u somuch......

    http://www.blogger.com/profile/05775925005917110551http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5435451572633243533http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2384841932782641712http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1967210455342925721http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1967210455342925721http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2384841932782641712http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5435451572633243533http://www.blogger.com/profile/05775925005917110551
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    25/34

    97. Anonymous (January 27, 2011 2:18 AM)thanks a lot for this tutorial. it was very helpful

    98. Anonymous (February 01, 2011 9:54 PM)Thank you very much, It was really helpful,thanks for your time

    99. Anonymous (February 04, 2011 9:57 AM)This comment has been removed by a blogadministrator.

    100. Rohan (February 15, 2011 9:31 PM)Nicely framed example. good job

    101. teahena (February 28, 2011 5:29 PM)hey pls give short n simplest small prg which canbe copy n implemented....

    102. sree (March 03, 2011 11:36 AM)Its really helpfull

    103. ashok kumar (March 22, 2011 12:15AM)

    really good tutorial, thanks.

    104. Anonymous (April 20, 2011 1:46 AM)very nice tutorial... easy to understand thecontent..thanksVelu

    105. fluxion (April 22, 2011 1:06 AM)So clean; but I have a question for you. SinceComparators would be added for each field andnewer fields, I was kind of thinking if we cancome up with Generic Comparator, like one forEmployee, another for Car. I can think ofcapturing field name into the comparator, using

    reflection build that getter method, and it should

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5499681326172510862http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4750695752543261978http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8603979021007275014http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4163833366973181788http://www.blogger.com/profile/01883403960705264649http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2310221192788406099http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2016608828225761607http://www.blogger.com/profile/09536399987765308480http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7354090034787841700http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7354090034787841700http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5707481174168732715http://www.blogger.com/profile/15190074169105825485http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4126843466239379739http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4126843466239379739http://www.blogger.com/profile/15190074169105825485http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5707481174168732715http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7354090034787841700http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7354090034787841700http://www.blogger.com/profile/09536399987765308480http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2016608828225761607http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2310221192788406099http://www.blogger.com/profile/01883403960705264649http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4163833366973181788http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8603979021007275014http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4750695752543261978http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5499681326172510862
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    26/34

    work I believe.

    106. Anonymous (May 25, 2011 7:03 PM)thanks

    regards gaurav g.

    107. Anonymous (June 15, 2011 1:30 AM)Wow, thanks a lot for clearing this up, you savedme hours of time.

    108. Sushanta Dutta (June 22, 2011 2:11PM)

    why equals() should be override in the context ofComparator/Comparable?? please send me thedetails discussion.

    109. Anonymous (July 02, 2011 6:33 PM)It's really Good

    110. Anonymous (July 05, 2011 4:49 PM)I don't understand the consistency between

    compare(),compareTo(), and equals().

    111. Anonymous (July 12, 2011 10:47 PM)Good article.

    112. Anonymous (July 26, 2011 5:30 PM)thanks...simple bt helpful

    113.

    Anonymous (July 27, 2011 6:13 AM)

    Good example, clearly explained.

    114. sateesh (August 04, 2011 6:36 PM)nice one. Able to clearly understand the concept.

    115. Anonymous (August 20, 2011 10:17AM)

    We are using Java 6 and in our case employeename may be alphanumeric... after sorting names

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7799880125759915372http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2419438999485082353http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5510760554409173662http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5510760554409173662http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c140890582920737810http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4839312066459761809http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5043935255217674725http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5628410245651911606http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8849534504704272307http://www.blogger.com/profile/16062755858953628115http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4328970073885211333http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7016280170435981746http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7016280170435981746http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7016280170435981746http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7016280170435981746http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4328970073885211333http://www.blogger.com/profile/16062755858953628115http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8849534504704272307http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5628410245651911606http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5043935255217674725http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c4839312066459761809http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c140890582920737810http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5510760554409173662http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5510760554409173662http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c2419438999485082353http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7799880125759915372
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    27/34

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

    116. Kamal Mettananda (August 21, 201112:23 PM)

    // 112.When a field is alphanumeric, I assume you arerepresenting that using a String. However whensorting you want to sort the values treatingnumeric values as numeric.So it would be easy for you to first check whetherthe String contains only digits and do numberbase sort first and String based sort for the rest.

    To find whether a String contains digits;Character.isDigit() method will help.

    http://lkamal.blogspot.com/2008/07/java-numbers-only-string-remove-non.html

    117. Anonymous (September 01, 2011 9:26AM)

    Very nicely explained :):)Thanks

    118. Anonymous (September 03, 2011 2:33AM)

    Thank you very helpful!

    119. Ethan (September 10, 2011 11:53AM)

    This really helps me a lot, thank you!!!

    120. Anonymous (September 18, 2011 9:06PM)

    This is a great tutorial. Thank You!

    121. Ravi (September 23, 2011 6:28 PM)Hi...This is nice blog..thank you for thisinformation..It helped me...+1ed it.

    122. Kamal Mettananda (September 23,

    http://www.blogger.com/profile/03241660835422874258http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5458316481783254704http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5458316481783254704http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1422963399681539726http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1422963399681539726http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8838684018843169891http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8838684018843169891http://www.blogger.com/profile/06880720272760660438http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c194411828657779773http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c194411828657779773http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7752621380855921612http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7752621380855921612http://www.blogger.com/profile/04035715103828812563http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c9202889597351244952http://www.blogger.com/profile/03241660835422874258http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6789023561998904369http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6789023561998904369http://www.blogger.com/profile/03241660835422874258http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c9202889597351244952http://www.blogger.com/profile/04035715103828812563http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7752621380855921612http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c7752621380855921612http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c194411828657779773http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c194411828657779773http://www.blogger.com/profile/06880720272760660438http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8838684018843169891http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8838684018843169891http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1422963399681539726http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1422963399681539726http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5458316481783254704http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c5458316481783254704http://www.blogger.com/profile/03241660835422874258
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    28/34

    2011 9:48 PM)

    @Ravi Thanks

    123. ANIL (September 29, 2011 7:41 PM)Employee class/bean is written twice and it hasthe different code, which one is supposed to beused for this or else how the packaginge need tobe done for running the example, pl guide

    Anil

    124. Anonymous (December 26, 2011 7:40PM)

    nice and short tutorial, cleared all my doubts

    125. Anonymous (December 30, 2011 2:55AM)

    Excellent demo.

    126. Kapil Garg (March 29, 2012 2:43 PM)great

    127. Anonymous (April 04, 2012 3:41 PM)Great Job done. :)Keep posting more articles.!

    128. peenu (May 11, 2012 12:43 AM)if I want to sort empname basis then itsworking.if empname are same then sorting itaccording to designation both empname anddesignation fields are string.plz answer.

    129. Glekko (May 11, 2012 5:01 AM)I have menu order as string with levels separatedwith dot (for instance it will be like 1.2.1 and1.2.2). This works fine with a sql order by whenthe last numbers are upto 9 but with 10 it comesas first. After i read ur article i was able to crackit.

    Thanks

    http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6789023561998904369http://www.blogger.com/profile/01554539736147152897http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1606187881340104266http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c173666484373109870http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c173666484373109870http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8545569863891723321http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8545569863891723321http://www.blogger.com/profile/10581465360767571962http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c772258759627902086http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8645796030523117022http://www.blogger.com/profile/14724882143462515163http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c973995702242009865http://www.glekko.com/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1301434081418362959http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1301434081418362959http://www.glekko.com/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c973995702242009865http://www.blogger.com/profile/14724882143462515163http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8645796030523117022http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c772258759627902086http://www.blogger.com/profile/10581465360767571962http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8545569863891723321http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c8545569863891723321http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c173666484373109870http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c173666484373109870http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c1606187881340104266http://www.blogger.com/profile/01554539736147152897http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.html#c6789023561998904369
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    29/34

    MAJOR SECTIONS

    Java Tips & Tutorials Important News Software Earning Online Money Web Designing

    FEED SUBSCRIPTION

    Subscribe to our feed using your online news reader, approximately 1-2 articles per week.NEWSLETTER SUBSCRIPTION

    Enter your email address:

    Delivered byFeedBurner

    ABOUT USThis seven years old blog is mainly focused on Computer Programming. However topics likeSoftware (Tools), Internet, Earning Online Money are discussed as required.

    You all are welcome to request tutorials/tips; also send us any news/tips onadmin(at)digizol(dot)org.

    Digizol byKamal Mettanandais licensed under aCreative Commons Attribution-Noncommercial-No Derivative Works 3.0 United States License .

    2004-2011

    ^top^

    Re: When to use Comparator and Comparable Interface

    in java

    Difference between Comparator and Comparable in Java1) Comparator in Java is defined in java.util package while Comparable interface in Java isdefined in java.lang package.2) Comparator interface in Java has method public int compare (Object o1, Object o2) whichreturns a negative integer, zero, or a positive integer as the first argument is less than, equalto, or greater than the second. While Comparable interface has method public int

    compareTo(Object o) which returns a negative integer, zero, or a positive integer as thisobject is less than, equal to, or greater than the specified object.

    http://www.digizol.org/search/label/Javahttp://www.digizol.org/search/label/Javahttp://www.digizol.org/search/label/Newshttp://www.digizol.org/search/label/Newshttp://www.digizol.org/search/label/Softwarehttp://www.digizol.org/search/label/Softwarehttp://www.digizol.org/search/label/Earn%20Onlinehttp://www.digizol.org/search/label/Earn%20Onlinehttp://www.digizol.org/search/label/Web%20Designhttp://www.digizol.org/search/label/Web%20Designhttp://feedburner.google.com/http://feedburner.google.com/http://feedburner.google.com/http://www.digizol.org/http://www.digizol.org/http://www.digizol.org/http://creativecommons.org/licenses/by-nc-nd/3.0/us/http://creativecommons.org/licenses/by-nc-nd/3.0/us/http://creativecommons.org/licenses/by-nc-nd/3.0/us/http://creativecommons.org/licenses/by-nc-nd/3.0/us/http://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://creativecommons.org/licenses/by-nc-nd/3.0/us/http://feeds2.feedburner.com/lkamal/rsshttp://creativecommons.org/licenses/by-nc-nd/3.0/us/http://feeds2.feedburner.com/lkamal/rsshttp://creativecommons.org/licenses/by-nc-nd/3.0/us/http://feeds2.feedburner.com/lkamal/rsshttp://www.digizol.org/2008/07/java-sorting-comparator-vs-comparable.htmlhttp://creativecommons.org/licenses/by-nc-nd/3.0/us/http://creativecommons.org/licenses/by-nc-nd/3.0/us/http://www.digizol.org/http://feedburner.google.com/http://www.digizol.org/search/label/Web%20Designhttp://www.digizol.org/search/label/Earn%20Onlinehttp://www.digizol.org/search/label/Softwarehttp://www.digizol.org/search/label/Newshttp://www.digizol.org/search/label/Java
  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    30/34

    3) If you see then logical difference between these two is Comparator in Java compare twoobjects provided to him, while Comparable interface compares "this" reference with theobject specified.4) Comparable in Java is used to implement natural ordering of object. In Java API String,Date and wrapper classes implement Comparable interface.

    5) If any class implement Comparable interface in Java then collection of that object eitherList or Array can be sorted automatically by using Collections.sort() or Array.sort() methodand object will be sorted based on there natural order defined by CompareTo method.6)Objects which implement Comparable in Java can be used as keys in a sorted map orelements in a sorted set for example TreeSet, without specifying any Comparator.

    Also Please find below the examples for using the Comparator and Comparable Interface

    1) There is class called Person, sort the Person based on person_id.2) Sort the Person based on Name.

    For a Person class sorting based on person_id can be treated as natural order sorting andsorting based on Name can be implemented using Comparator interface. To sort based onperson_id we need to implement compareTo() method.

    public class Person implements Comparable {private int person_id;private String name;

    /*** Compare current person with specified person* return zero if person_id for both person is same* return negative if current person_id is less than specified one* return positive if specified person_id is greater than specified one*/public int compareTo(Person o) {return this.person_id - o.person_id ;}.}

    And for sorting based on person name we can implement compare (Object o1, Object o2)method of Comparator in Java or Java Comparator class.

    public class PersonSortByPerson_ID implements Comparator{

    public int compare(Person o1, Person o2) {return o1.getPersonId() - o2.getPersonId();}}

    import java.util.ArrayList;import java.util.Arrays;

    import java.util.Collections;

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    31/34

    import java.util.Comparator;

    import java.util.List;

    public class EmpComparator implements Comparator {

    public int compare(Object obj1, Object obj2) {

    Person emp1 = (Person) obj1;

    Person emp2 = (Person) obj2;

    int nameComp = emp1.getFirstName().compareTo(emp2.getFirstName());

    return ((nameComp == 0) ? emp1.getLastName().compareTo(

    emp2.getLastName()) : nameComp);

    }

    public static voidmain(String args[]) {

    String names[] = { "Bart", "Hugo", "Lisa", "Marge", "Homer", "Maggie",

    "Roy" };

    // Convert to list

    List list = new ArrayList(Arrays.asList(names));

    // Ensure list sorted

    Collections.sort(list);

    System.out.println("Sorted list: [length: " + list.size() + "]");

    System.out.println(list);

    // Search for element in list

    int index = Collections.binarySearch(list, "Maggie");

    System.out.println("Found Maggie @ " + index);

    // Search for element not in list

    index = Collections.binarySearch(list, "Jimbo Jones");

    System.out.println("Didn't find Jimbo Jones @ " + index);

    // Insert

    int newIndex = -index - 1;

    list.add(newIndex, "Jimbo Jones");

    System.out.println("With Jimbo Jones added: [length: " + list.size()

    + "]");

    System.out.println(list);

    // Min should be Bart

    System.out.println(Collections.min(list));

    // Max should be Roy

    System.out.println(Collections.max(list));

    Comparator comp = Collections.reverseOrder();

    // Reversed Min should be Roy

    System.out.println(Collections.min(list, comp));

    // Reversed Max should be Bart

    System.out.println(Collections.max(list, comp));

    }

    }

    class Person implements Comparable {

    String firstName, lastName;

    public Person(String f, String l) {

    this.firstName = f;this.lastName = l;

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    32/34

    }

    public String getFirstName() {

    return firstName;

    }

    public String getLastName() {return lastName;

    }

    public String toString() {

    return "[ name=" + firstName + ",name=" + lastName + "]";

    }

    public int compareTo(Object obj) {

    Person emp = (Person) obj;

    int deptComp = firstName.compareTo(emp.getFirstName());

    return ((deptComp == 0) ? lastName.compareTo(emp.getLastName())

    : deptComp);}

    public boolean equals(Object obj) {

    if (!(obj instanceof Person)) {

    return false;

    }

    Person emp = (Person) obj;

    return firstName.equals(emp.getFirstName())

    && lastName.equals(emp.getLastName());

    }

    }

    /****************************************************************************************************************************************************************/

    import java.util.Arrays;

    import java.util.Collections;

    import java.util.Comparator;

    import java.util.Set;

    import java.util.TreeSet;

    public class Company {

    public static voidmain(String args[]) {

    Employee emps[] = { new Employee("Finance", "Degree, Debbie"),

    new Employee("Finance", "Grade, Geri"),

    new Employee("Finance", "Extent, Ester"),

    new Employee("Engineering", "Measure, Mary"),

    new Employee("Engineering", "Amount, Anastasia"),

    new Employee("Engineering", "Ratio, Ringo"),

    new Employee("Sales", "Stint, Sarah"),

    new Employee("Sales", "Pitch, Paula"),

    new Employee("Support", "Rate, Rhoda"), };

    Set set = new TreeSet(Arrays.asList(emps));

    System.out.println(set);

    Set set2 = new TreeSet(Collections.reverseOrder());

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    33/34

    set2.addAll(Arrays.asList(emps));

    System.out.println(set2);

    Set set3 = new TreeSet(new EmpComparator());

    for (int i = 0, n = emps.length; i < n; i++) {

    set3.add(emps[i]);

    }

    System.out.println(set3);

    }

    }

    class EmpComparator implements Comparator {

    public int compare(Object obj1, Object obj2) {

    Employee emp1 = (Employee) obj1;

    Employee emp2 = (Employee) obj2;

    int nameComp = emp1.getName().compareTo(emp2.getName());

    return ((nameComp == 0) ? emp1.getDepartment().compareTo(

    emp2.getDepartment()) : nameComp);

    }

    }

    class Employee implements Comparable {

    String department, name;

    public Employee(String department, String name) {

    this.department = department;this.name = name;

    }

    public String getDepartment() {

    return department;

    }

    public String getName() {

    return name;

    }

    public String toString() {

    return "[dept=" + department + ",name=" + name + "]";

    }

    public int compareTo(Object obj) {

    Employee emp = (Employee) obj;

    int deptComp = department.compareTo(emp.getDepartment());

    return ((deptComp == 0) ? name.compareTo(emp.getName()) : deptComp);

    }

    public boolean equals(Object obj) {if (!(obj instanceof Employee)) {

  • 7/31/2019 Home Tutorials News Software Online Money Web Designing

    34/34