Saturday, March 10, 2018

Java Comparable vs Comparator



https://www.journaldev.com/780/comparable-and-comparator-in-java-example

Comparable vs Comparator

  1. Comparable interface can be used to provide single way of sorting whereas Comparator interface is used to provide different ways of sorting.
  2. For using Comparable, Class needs to implement it whereas for using Comparator we don’t need to make any change in the class.
  3. Comparable interface is in java.lang package whereas Comparator interface is present in java.util package.
  4. We don’t need to make any code changes at client side for using Comparable, Arrays.sort() or Collection.sort() methods automatically uses the compareTo() 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

java special for collection size, array size, and string size

Size: For Collections (eg: Map, List, etc ): usually it use collection.size(), eg         Map<Character, Integer> map ...