Tuesday, December 20, 2011

Differences between Comparator and Comparable

Following is a table of the differences between java.util.Comparator and  java.lang.Comparable  interfaces. If I have missed any point, please notify me of that.

The implementation of java.util.Comparator and java.lang.Comparable can be found at
Comparator and
Comparable respectively.



Comparator
Comparable
Package
Java.util
Java.lang
Method
public int compare (Object o1, Object o2)

returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second
public int compareTo(Object o)

returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object
Main Difference
Compares 2 objects provided to it.
Compares this object to the object given.


Used to implement natural ordering of objects. Implemented by String, Date and wrapper classes.


If any class implements Comparable interface 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.
Implementation
Normally, for a bean named Employee(String name, String Department, int Age), if we want to implement a name comparator, we need two classes: bean class(Employee) and comparator class as
public class Employee {} And
public class EmployeeNameComparator implements Comparator{}
For a bean name Employee(String name, String Department, int Age), if we want to implement a name comparable, we do not need to create a new class but instead we will implement it through the same Employee class as
public class Employee implements Comparable{}




No comments:

Post a Comment