The classes that implements Comparable interface support default natural sorting, if one needs to implement a customized sorting order then Comperator comes into picture. Further, the classes which doesn’t implement Comparable interface and required a need to support for sorting, then Comparator can also be used in such case.
For user-defined classes, Comparator can be used for sorting objects based on some values as a base for determining order of elements.
1. Comparable is for default natural sorting, on other hand, Comparator is for custom sorting
2. Comparable resides in java.lang package, whereas, Comparator comes under java.util package
3. Comparable interface consists only single method, named compareTo(), while Comparator contains 2 method, named equals() and compare()
4. All wrapper classess & String implements Comparable interface, whereas, Collator or RuleBaseCollator are two classes that directly implement Comparator .
Basis | Comparable | Comparator |
---|---|---|
Definition | It defines the natural sorting order of elements in a class | It provides a way to define a custom sorting order for elements in a class |
Method | It provides compareTo() method that is required to implemented by a class | It provides compare() method that is required to implemented by a class |
Object Type | Can only be used with objects of the same type and comparable | Using Comparator, we can use non comparable objects in a class |
Sorting Order | Sorting order is determined by the class's implementation of the compareTo() method | Sorting order is determined by the implementation of the compare() method in the Comparator implementation |
Collections.sort() | Collections.sort(list) can be used to sort a collection of objects that implement Comparable | Collections.sort(list,comparatorObj) can be used to sort a collection of objects by passing a Comparator object as a parameter |
Ordering | Only one ordering can be defined for a class | Multiple orderings can be defined for a class by creating multiple Comparator objects |
Package | It resides in java.lang package | It resides in java.util package |