Java / Collections
Difference between Comparable and Comparator interface.
Comparable. | Comparator. |
Class whose objects to be sorted must implement this interface and to implement compareTo(Object) method. | Class whose objects to be sorted do not need to implement this interface. Instead a third class can implement this interface to sort and implement compare method. |
Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects. | Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. |
Collections.sort(List). Objects will be sorted on the basis of CompareTo method. | Collections.sort(List, Comparator). Objects will be sorted based on the Compare method in Comparator. |
Comparable located in Java.lang package. | Comparator located in Java.util package. |
More Related questions...