java tutorial - Difference between Comparable and Comparator - java programming - learn java - java basics - java for beginners
- Comparable and Comparator is an interface used to sort gathering elements.
Differences between Comparable and Comparator interfaces are:
Comparable | Comparator |
---|---|
1) Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc. | Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc. |
2) Comparable affects the original class i.e. actual class is modified. | Comparator doesn't affect the original class i.e. actual class is not modified. |
3) Comparable provides compareTo() method to sort elements. | Comparator provides compare() method to sort elements. |
4) Comparable is create in java.lang package. | Comparator is create in java.util package. |
5) Sort the list elements of Comparable type by Collections.sort(List) method. | Sort the list elements of Comparator type by Collections.sort(List,Comparator) method. |