Tuesday, 26 July 2011

Comparable versus Comparator

Comparable and Comparator are both used to compare objects.

In case of Comparable interface,
  1. The object o1 (class of which implements the interface) is compared to the object o2 which is passed as method argument [NOTE: public int compareTo(Object o2) ]
  2. If the o1 is greater than o2 then the method will return +ve integer and -ve if lesser than o2, if both are equal then 0 value is returned.
  3. It should be used when you want to define natural/default ordering of a class, if the class is available for modification (remember? a third party class isn't available for modification)
  4. if one add two keys a and b such that (!a.equals(b) && a.compareTo(b)==0) to a sorted set that does not use an explicit comparator, then the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set's perspective.
In case of Comparator interface,
  1. The Class which implements this interface will take two objects and compare them with each other. [NOTE: public int compare(Object o1, Object o2)
  2. If the o1 is greater than o2 then the method will return +ve integer and -ve if lesser than o2, if both are equal then 0 value is returned.
  3. If the class isn't available for modifying or if you want to define ordering which is other than the default then use the Comparator interface.
  4. If one add two keys a and b such that (a.equals(b) && c.compare(a,b)!=0) to a sorted set with comparator c, then the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set's perspective.
Resources

No comments:

Post a Comment