Difference between Comparator and Comparable in java collection with example
GIAN Tutorials
7:33 AM
Comparable interface: Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method. For example: 1 2 3 4 5 6 7 public class Country implements Comparable { @ Override public int compareTo ( Country country ) { return ( this . countryId < country . countryId ) ? - 1 : ( this . countryId > country . countryId ) ? 1 : 0 ; } } If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class. Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface. Comparator interface: Class whose objects to be sorted ...