+ 1
Difference between comparator and comparable?
3 Answers
+ 4
Comparable and comparator both are an interface that can be used to sort the elements of the collection. Comparator interface belongs to java.util package while comparable belongs to java.lang package.
+ 4
Ajay
Usage of Java function Arays.sort() and Collection.sort(): If you are using Comparable for Sorting then you can use Arrays.sort() and Collections.sort() for sorting directly. You do not need to provide a comparator. You just need to call the method.
Provide ease for TreeMap and TreeSet: Here I want to suggest you please read TreeMap and TreeSet. Because TreeMap and TreeSet also use the Comparator and Comparable.
If your implementing Comparable interface in your class, then objects of that class can be used as keys in a TreeMap or as elements in a TreeSet. But if you are using Comparator interface then you have to write separate Comparator and pass it in the constructor of TreeMap or TreeSet.
Number of classes:Â To implement the Comparator interface you have provides extra classes. There is some situation where you do not want to write extra class the you should go with Comparable interface.
https://javagoal.com/diff-between-comparable-and-comparator/
+ 4
https://www.sololearn.com/post/230607/?ref=app