Sunday, 1 May 2011

Difference between Comparable and Comparator Interface

Key Difference between Comparable and Comparator interface

The key difference between comparable and comparator interface is:

Comparable Interface Comparator Interface
The comparable interface should be used when the current object is to be compared to objects of its type only.
The comparator should be used when some external class is taking your class as a parameter for some comparison operation and it doesn't know how to compare the objects and expects you to give it. In this case you can't give your class as the comparator. It has to be some other class which implements comparator interface and does the comparison.

The above is what we will learn from the following discussion about the two interfaces.

Comparable Interface

Lets start with the comparable interface:
The comparable interface is present in java.lang package. This means that you need not import this interface when you are implementing this interface.
This interface has only one method which has the signature as:

public int compareTo(Object o);

As the name suggests you want this object to be compared to someone else. In Java syntax, the code is:

CompareClass cmp1 = new CompareClass();
CompareClass cmp2 = new CompareClass();
cmp1.compareTo(cmp2);


The best definition of this interface will be the one given in Java API which is reproduced here:
This interface imposes a total ordering on the objects of each class that implements it

Its all upto the implementor to decide how and which kind of objects will he be comparing with the Object for which compareTo method has been invoked. Some facts related to comparable interface are as follows:
1) The compareTo() method should return -ve,zero or +ve integer depending upon whether this object is less than,equal to or greater than the specified object
2) The value returned by compareTo() should be consistent with the value returned by equals() method of the same class. if not so, the class should explicitly state that.
3) Any comparison with null should throw NullPointerException
4)If the object of the classes which implement this interface can be used as keys in the SortedMap or SortedSet.
5)Lists and Arrays that implemet this interface can be sorted using the Collections.sort(List/Array) method without specifying any external comparator.
Example: Lets take the example of String class. Here is a sample code which will clear the compareTo method for you:

public class Test
{
public static void main(String[] args)
{
String str1 = "bar";
String str2 = "barfoo";

int compareResult = str1.compareTo(str2);
if (compareResult < 0){
System.out.println(str1 + "is less than" + str2);
}else if (result == 0){
System.out.println(str1 +"is equal to" + str2);
}else{
System.out.println(str1 +"is greater than" + str2);
}
}
}





In this example, we are comparing String objects with other String objects and the comparTo method resides within the String class itself.


Comparator Interface



Now lets see the comparator interface.
The Comparator interface is a part of util package and needs to explicitly imported.
The general contract that is true for comparable is also true for comparator interface which is restated here because of its importance.
The value returned by the compare method of the class implementing the comparator interface should also return the same value with equals() method. This is important because the SortedSet and SortedMap will behave strangely.
There are two methods specified in the comparator interface which have the signature as follows:


int compare(T o1, T o2);
boolean equals(Object obj);


The compare() method should return -ve,zero or +ve integer depending upon whether this object is less than,equal to or greater than the specified object


Example:


import java.util.*;
class Test{

private int prop1;
public void setProp1(int prop1){
this.prop1=prop1;
}

public int getProp1(){
return this.prop1;
}
}


class TestComparator implements Comparator{

public int compare(Object obj1, Object obj2){
int test1 = ( (Test) obj1).getProp1();
int test2 = ( (Test) obj2).getProp1();

if( test1 > test2 )
return 1;
else if( test1 < test2 )
return -1; else return 0;
}
}


So whats the distinguishing part between the comparable and comparator?
Well its the difference in terms of the method signature at code level.
But in terms of design level, there is a big difference and should not be overlooked.
The comparable interface should be used when the current object is to be compared to objects of its type only.
The comparator should be used when some external class is taking your class as a parameter for some comparison operation and it doesn't know how to compare the objects and expects you to give it. In this case you can't give your class as the comparator. It has to be some other class which implements comparator interface and does the comparison. A typical example of this is the Collections.sort(List l, Comparator c) method.

No comments:

Post a Comment