Monday, 10 October 2011

How to use Comparator and Comparable in Java? With example

Comparators and comparable in Java are two of fundamental interface of Java API which is very important to understand toimplement 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 () andcompare 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 whileComparable 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 implementComparable 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 Array.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

compareto,compare to java,compare to 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 implementcompare (Object o1, Object o2) method of Comparator in Java orJava 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 numberbased upon logical results.


How to Compare String in Java

comparator in java,compare to java,java comparator example
For comparing String in Java we should not be worrying because StringimplementsComparable interface in Java and provides implementation for CompareTo method which Compare two strings based on  characters inside or you can say in lexical order. You just need to call String.compareTo(AnotherString) and Java will determine whether specified String is greater than , equal to or less than current String. String is also immutable in Java an important property to remember.



How to Compare Dates in Java

Dates are represented by java.util.Date class in Java and like String Dates alsoimplementsComparable in Java so they will be automatically sorted based on there natural ordering if they got stored in any sorted collection like TreeSet or TreeMap. If you explicitly wants to compare two dates in Java you can call Date.compareTo(AnotherDate) method in Java and it will tell whether specified date is greater than , equal to or less thancurrent String.


This article is in continuation of my previous articles How Classpath works in Java and How to write Equals method in java  and How to use Arraylist in Java using generics  so if you haven’t read those you may find it interesting.

No comments:

Post a Comment