Difference between comparator and comparable? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Difference between comparator and comparable?

20th Aug 2020, 7:02 AM
Ajay✨
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.
20th Aug 2020, 7:15 AM
Vishakha Shrivastav
Vishakha Shrivastav - avatar
+ 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/
20th Aug 2020, 2:47 PM
Raina Dhankhar
Raina Dhankhar - avatar
+ 4
https://www.sololearn.com/post/230607/?ref=app
21st Aug 2020, 1:29 AM
P∆WAN M∆URY∆
P∆WAN M∆URY∆ - avatar