Comparable vs Comparator in Java

Here you will learn about Comparable vs Comparator in Java.

Difference between Comparable and Comparator is one of the commonly asked questions in Java interviews. Both the interfaces are used to sort collection objects but still there are some differences between them which I have discussed below.

Also Read: Comparable and Comparator Example

Comparable vs Comparator in Java
Image Source

Comparable vs Comparator in Java

S.No Comparable Comparator
1. It is used to sort objects on the basis of only one property at a time. For example if you want to sort data of employees then you can do this either on the basis of id, age or name. It can be used to sort objects on the basis of more than one property at a time. For example if you want to sort data of employees then you can do this on the basis of id, age and name.
2. The class whose objects are to be sorted must implement Comparable interface. The original class is modified. The class whose objects are to be sorted need not to implement Comparator interface. The original class is not modified.
3. It provides compareTo() method for sorting. It has following syntax.

int compareTo(Object o1)

 

It returns following value:

positive: if this object is greater than  o1

negative: if this object is less than o1

zero: if this object is equal to o1

It provides compare() method for sorting. It has following syntax.

int compare(Object o1, Object o2)

 

It returns following value:

positive: if o1 is greater than  o2

negative: if o1 is less than o2

zero: if o1 is equal to o2

4. Comparable is defined in java.lang package. Comparator is defined in java.util package.
5. Objects are sorted by calling Collections.sort(List) method. Objects are sorted by calling Collections.sort(List, Comparator) method.

 

Comment below if you have doubts or found anything incorrect in above Comparable vs Comparator tutorial.

1 thought on “Comparable vs Comparator in Java”

Leave a Comment

Your email address will not be published. Required fields are marked *