When to use Comparable, and when Comparator?

  • one
    In theory, the same as the difference between "compared" from "comparator" - Kromster

1 answer 1

Classes implement Comparable , so that you can then sort by implementing the compareTo(Object) method.

If the class implements this interface, then you can use Collection.sort() or Arrays.sort() . Objects will be sorted based on the implementation of the compareTo(Object) method.

For example:

 public class Country implements Comparable<Country>{ @Override public int compareTo(Country country) { return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ; } } 

When calling Collection.sort() on collections of objects of this class, they will be compared based on compareTo(Country country) .

And the Comparator used to implement sorting by a custom field, like:

 List<Country> listOfCountries = new ArrayList<Country>(); [...] Collections.sort(listOfCountries,new Comparator<Country>() { @Override public int compare(Country o1, Country o2) { return o1.getCountryName().compareTo(o2.getCountryName()); } }); 

Objects will be sorted based on a comparison of country names.

To summarize, then:

Comparable - implemented inside the class. In essence, it defines the usual / natural order of comparing objects.

Comparator - implemented outside the class. You can implement different sorting options based on a comparison of different fields.