Comparators and comparable Interface

Comparators and comparable:

Comparators and comparable 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:


  • Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package.
  • 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.
  • 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.
  • Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.
  • 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.
  • 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:


So in Summary if you want to sortbased on natural order or object then useComparable 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

  •  There is class called Person, sort the Person based on person_id.
  •  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 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:


For comparing String in Java we should not be worrying because String implements Comparable 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:


Dates are represented by java.util.Date class in Java and like String Dates also implements Comparable 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 than current String.

 *******************************************************************************
Reach us At: - 0120-4029000 / 24 / 25 / 27 / 29 Mobile: 9953584548
Write us at: - Smruti@apextgi.com and pratap@apextgi.com

No comments:

Post a Comment