Difference Between Comparator and Comparable Interface

Category: Java   Tags: Java, Java Collection, Java Comparator Interface, Java Comparable Interface

Before going to the difference, you can go through Java Comparator Interface and Java Comparable Interface in details.

1.

Comparable: You have to implement Comparable interface to the same class whose objects are being sorted.

Comparator: Sorting logic is written to different class and use that class as comparator. Hence we can write different sorting based on different attributes of objects to be sorted.

2.

Comparable: Use int compareTo(Object o) method for comparison. It compares this object with the specified object o for ordering.

Returns -ve integer if this object < o
Returns 0 if this object == o
Returns +ve integer if this object > o

Comparator: Use int compare(Object o1, Object o2) method for comparison. It compares its two arguments o1 and o2 for ordering.

Returns -ve integer if o1 < o2
Returns 0 if o1 == o2
Returns +ve integer if o1 > o2

3.

Comparable: Use Collections.sort(List) to sort the list.

Comparator: Use Collections.sort(List, Comparator) method to sort the list. Here objects will be sorted on the basis of Compare method in Comparator

4.

Comparable: It is inside Java.lang.Comparable

Comparator: It is inside Java.util.Comparator