Comparable and Comparator both are interfaces and can be used to sort collection elements.
But there are many differences between Comparable and Comparator interfaces that are given below.
Comparable
|
Comparator
|
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.
|
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.
|
Comparable provides compareTo() method to sort elements.
|
Comparator provides compare() method to sort elements.
|
Comparable is found in java.lang package.
|
Comparator is found in java.util package.
|
We can sort the list elements of Comparable type byCollections.sort(List) method.
|
We can sort the list elements of Comparator type byCollections.sort(List,Comparator) method.
|
No comments:
Post a Comment