Difference between Comparator and Comparable
|It is available in java.util package.||It is available in java.lang package.|
|We need to override compare() method.||We need to override compareTo() method.|
|It takes two arguments as parameters.|
public int compare(Object obj1,Object obj2 )
| It takes only one argument as a parameter.|
public int compareTo(Object obj)
|Its primary use is where we need to write the comparing logic outside the class which has to be compared.||It is used when we need to compare the instance of an object with a given object. Comparing logic is inside the class that needs to be compared.|
|this reference is not made while comparing objects||this reference is used to compare the object.|
|It is used for comparing objects based on any logic.||It is mostly used for comparing objects based on the natural ordering.|
Points To Remember
- Both compareTo() and compare() methods return int value.
- Both compareTo() and compare() methods return either a negative integer, 0 or a positive integer.
- Both Comparator and Comparable are interfaces.