«Back to Home

Core Java

Topics

Difference Between Comparable and Comparator In Java

In Java, both comparable and comparator are the interfaces and both can be used to sort the collection elements.
 
Differentiate Between Comparable and Comparator

In Java, there are many differences between comparable and comparator interfaces, which are,

 Comparable  Comparator
Comparable interface provides single sorting sequence only. This means we can sort the collection on the basis of the single element for example Id or name. Comparator interface provides the multiple sorting sequences. This means we can sort the collection on the basis of the multiple elements for example id and name.
Comparable interface affects the original class i.e. an actual class is modified. Comparator interface doesn't affect the original class i.e. an actual class is not modified.
Comparable interface gives compareTo () method to sort the elements. Comparator interface gives compare () method to sort the elements.
Comparable interface is found in java.lang package. Comparator interface is found in java.util package.
We can sort the list elements of comparable type with Collections.sort (List) method.  
We can sort the list elements of comparator type with Collections.sort (List,Comparator) method.
 
Summary

Thus, we learnt that both comparable and comparator are the interfaces and both can be used to sort the collection elements and also learnt their differences in Java.