Javatpoint Logo

Difference between Comparator and comparable interfaces in collections?

By: vivek.*** On: Sat Nov 01 04:07:02 IST 2014     Question Reputation0 Answer Reputation0 Quiz Belt Series Points0  0Blank User
You just have provided the examples there but I couldn't find the difference between them.Up0Down

 
Difference between Comparator and Comparable in java

One of the common interview question is "What are differences between Comparator and Comparable". or "How will you sort collection of employee objects by its id or name".For that we can use two interfaces.i.e. Comparator and Comparable.Before we actually see differences,let me give you brief introduction of both.
Comparable interface:
Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method.
For example:
view plainprint?

public class Country implements Comparable<Country>{
@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 do not need to implement this interface.Some third class can implement this interface to sort.e.g.CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id. For example:
view plainprint?

public class CountrySortByIdComparator implements Comparator<Country>{

@Override
public int compare(Country country1, Country country2) {

return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
}

}

Using Comparator interface,we can write different sorting based on different attributes of objects to be sorted.You can use anonymous comparator to compare at particular line of code. For example:
view plainprint?

Country indiaCountry=new Country(1, "India");
Country chinaCountry=new Country(4, "China");
Country nepalCountry=new Country(3, "Nepal");
Country bhutanCountry=new Country(2, "Bhutan");

List<Country> listOfCountries = new ArrayList<Country>();
listOfCountries.add(indiaCountry);
listOfCountries.add(chinaCountry);
listOfCountries.add(nepalCountry);
listOfCountries.add(bhutanCountry);

//Sort by countryName

Collections.sort(listOfCountries,new Comparator<Country>() {

@Override
public int compare(Country o1, Country o2) {

return o1.getCountryName().compareTo(o2.getCountryName());
}
});
Image Created0Down

By: [email protected] On: Sat Nov 01 12:32:46 IST 2014 Question Reputation0 Answer Reputation0 Belt Series Points0 0User Image
Are You Satisfied :0Yes0No