What is the difference between Comparable and Comparator?
When to use Comparable and when to use Comparator?
2 answers
Classes implement Comparable
, so that you can then sort by implementing the compareTo(Object)
method.
If the class implements this interface, you can then use Collection.sort()
or Arrays.sort()
. The 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 a collection of objects of this class, they will be compared based on compareTo(Country country)
.
And Comparator
is used to implement sorting by custom field, tipo:
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());
}
});
The objects will be sorted based on the comparison of the country names.
To summarize, then:
Comparable
- implemented inside the class. Essentially, it defines the normal / natural order of comparing objects.
Comparator
- implemented outside the class. You can implement different sorting options based on comparing different fields.
Comparable-implemented by the class itself when the natural sort order is needed. An example is the String class.
Comparator-implemented by other classes. Allows you to separate the comparison implementation from the class and make several comparison implementations for different parameters for the same class.
| Comparable | Comparator
Package | java.lang | java.util
Functional Interface | Yes | Yes
Method | int o1.compareTo(o2) | int comparator.compare(o1, o2)
-1 if | o1 < o2 | Same
1 if | o1 > o2 | Same
0 if | o1 == o2 | Same
Implement | Class itself | Separate classes
Defines | Natural ordering | Sorting by different parameters
Examples | String, Date, Wrappers | For third-party classes