Tuesday, May 10, 2011

Difference between Compareble and Comparator interface

What is difference between Comparable and Comparator interface
1)
Comparable interface is in java.lang package
Comparator interface is in java.util package
================================
2)
int compareTo(Object o1) method takes input as only object
int compare(Object o1, Objecto2) method takes input as 2 object
================================
3)
java.lang.Comparable: int compareTo(Object inuptObject1)
This method compares this object with inputObject1. Returned int value has the following meanings.

   1. positive (this) object is greater than inuptObject1
   2. zero     (this) object equals to inuptObject1
   3. negative (this) object is less than inuptObject1


java.util.Comparator: int compare(Object object1, Object object2)
This method compares object1 and object2 objects. Returned int value has the following meanings.

   1. positive  object1 is greater than object2
   2. zero      object1 equals to object2
   3. negative  object1 is less than object2

===============================================
===============================================
Why do we need tow interface for object comparison?
Ans With Comparable you can not add comparison by custom attribute. or more specific you can not sort or  compare object with more than  one attribute.

2 comments:

  1. Nice article, by the way here is my list of differences:
    1) comparable in Java is used for natural ordering while Comparator is for custom sorting.
    2) Comarable in java.lang package while Comparator is java.util
    3) Comparable requires CompareTo() method while Comparator requires compare() method
    4) CompareTo() is used in SortedSet and SortedMap e.g. TreeSet and TreeMap.
    5) compareTo must be compatible with equals method in Java i.e. if two objects are equal via equals method compareTo method must return "0" for them, failing this may result in some subtle bug when you store those objects in collection class like TreeSet and TreeMap.
    source: http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html

    ReplyDelete