`
iloveflower
  • 浏览: 76762 次
社区版块
存档分类
最新评论
  • iloveflower: 呵呵。好好学习。。。。。。。。。。。。
    java 读书
  • Eric.Yan: 看了一点,不过是电子版的……你这一说到提醒我了,还要继续学习哈 ...
    java 读书

How to use Comparator and Comparable in Java? With example

 
阅读更多
Read more: http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html#ixzz1uaFRiHo5

What is Difference between Comparator and Comparable in Java question was asked in a Test paper for one of big Investment bank first round of interview. It was not that straight forward but it was related to how you will sort Employee object based on his EmployeeID and his name and that involves the use of both Comparable and Comparator in Java.

Comparators and comparable in Java are two of fundamental interface of Java API which is very important to understand to implement sorting in Java. It’s often required to sort objects stored in any collection class or in Array and that time we need to use compare () and compare To () method defined in java.util.Comparator and java.lang.Comparable class. Let’s see some important points about both Comparable and Comparator in Java before moving ahead

Difference between Comparator and Comparable in Java
1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package.

2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, 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 this object is less than, equal to, or greater than the specified object.

3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object 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 either List or Array can be sorted automatically by using  Collections.sort() or Arrays.sort() method and 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 or elements in a sorted set for example TreeSet, without specifying any Comparator.


Example of using Comparator and Comparable in Java

So in Summary if you want to sort based on natural order or object then use Comparable in Java and if you want to sort on some other attribute of object then Comparator in Java  is the way to go. Now to understand these concepts lets see an example

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 and sorting based on Name can be implemented using Comparator interface. To sort based on person_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();
    }
}

You can write several types of Java Comparator based upon your need for example  reverseComparator , ANDComparator , ORComparator etc which will return negative or positive number based upon logical results.

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics