https://www.journaldev.com/780/comparable-and-comparator-in-java-example
Comparable vs Comparator
- Comparable interface can be used to provide single way of sorting whereas Comparator interface is used to provide different ways of sorting.
- For using Comparable, Class needs to implement it whereas for using Comparator we don’t need to make any change in the class.
- Comparable interface is in
java.lang
package whereas Comparator interface is present injava.util
package. - We don’t need to make any code changes at client side for using Comparable,
Arrays.sort()
orCollection.sort()
methods automatically uses thecompareTo()
method of the class. For Comparator, client needs to provide the Comparator class to use in compare() method.
Arrays.sort() or Collection.sort()// using default comparTo <--- the objects must implements Comparable
Arrays.sort(myArray, myArrayComparator) or Collection.sort(myList, myListComparator)// using Comparator compare(Object o1, Object o2) <--- the comparator for the objects
No comments:
Post a Comment