April 06, 2016

#Java: Part 11-Core Java Interview Questions and Answers: Comparator vs Comparable

> > #Java: Part 10-Core Java Interview Questions and Answers

Difference between Comparator and Comparable in Java

Comparable and Comparator both are interfaces and can be used to sort collection elements.
Comparable Interface
Class whose objects to be sorted must implement this interface. In this,we have to implement compareTo(Object) method.

Example :
#####
public class Country implements Comparable{
    int countryId;
    String countryName;

    public Country(int countryId, String countryName) {
        super();
        this.countryId = countryId;
        this.countryName = countryName;
    }

    @Override
    public int compareTo(Object arg0) {
        Country country=(Country) arg0;
        return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ;
    }

    //getter setter methods of countryId and countryName
}

#####
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ComparatorMain {
    public static void main(String[] args) {
         Country indiaCountry=new Country(2, 'India');
         Country germanyCountry=new Country(1, 'Germany');
         Country canadaCountry=new Country(3, 'Canada');
         List listOfCountries = new ArrayList();
         listOfCountries.add(indiaCountry);
         listOfCountries.add(germanyCountry);
         listOfCountries.add(canadaCountry);

        Collections.sort(listOfCountries);
        System.out.println("After Sorting the collection..");
        for (int i = 0; i < listOfCountries.size(); i++) {
            Country country=(Country) listOfCountries.get(i);
            System.out.println("Country ID: "+country.getCountryId()+"|| "+"Country Name: "+country.getCountryName());
        }
    }
}

#####
Output of ComparatorMain is
After Sorting the collection..
Country ID: 1|| Country Name: Germany
Country ID: 2|| Country Name: India
Country ID: 3|| Country Name: Canada

Comparator Interface
Class whose objects to be sorted do not need to implement this interface.Some third class can implement this interface to sort.

Example:  We will create class country having attribute id and name and will create another class CountrySortByIdComparator which will implement Comparator interface and implement compare method to sort collection of country object by id and we will also see how to use anonymous comparator.

#####
public class Country{
    int countryId;
    String countryName;

    public Country(int countryId, String countryName) {
        super();
        this.countryId = countryId;
        this.countryName = countryName;
    }

    //getter setter methods of countryId and countryName
}

#####
import java.util.Comparator;
 public class CountrySortByIdComparator implements Comparator{
    @Override
    public int compare(Country country1, Country country2) {
        return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ;
    }
}

#####
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ComparatorMain {
    public static void main(String[] args) {
        Country indiaCountry=new Country(2, 'India');
        Country germanyCountry=new Country(1, 'Germany');
        Country canadaCountry=new Country(3, 'Canada');

        List listOfCountries = new ArrayList();
        listOfCountries.add(indiaCountry);
        listOfCountries.add(germanyCountry);
        listOfCountries.add(canadaCountry);
        //sort by ID
        Collections.sort(listOfCountries,new CountrySortByIdComparator());
        System.out.println("After Sorting the collection by id..");
        for (int i = 0; i < listOfCountries.size(); i++) {
            Country country=(Country) listOfCountries.get(i);
            System.out.println("Country ID: "+country.getCountryId()+"|| "+"Country Name: "+country.getCountryName());
        }
        //sort by Name
        Collections.sort(listOfCountries,new Comparator() {
                @Override
                public int compare(Country o1, Country o2) {
                    return o1.getCountryName().compareTo(o2.getCountryName());
                }
            });

        System.out.println("After Sorting the collection by Name..");
        for (int i = 0; i < listOfCountries.size(); i++) {
            Country country=(Country) listOfCountries.get(i);
            System.out.println("Country ID: "+country.getCountryId()+"|| "+"Country Name: "+country.getCountryName());
        }
    }
}

#####
Output of ComparatorMain is
After Sorting the collection by id..
Country ID: 1|| Country Name: Germany
Country ID: 2|| Country Name: India
Country ID: 3|| Country Name: Canada
After Sorting the collection by Name..
Country ID: 3|| Country Name: Canada
Country ID: 1|| Country Name: Germany
Country ID: 2|| Country Name: India

Difference between Comparable and Comparator:
  1. Comparable provides single sorting sequence. In other words, we can sort the collection on the basis of single element such as id or name or price etc. And Comparator provides multiple sorting sequence. In other words, we can sort the collection on the basis of multiple elements such as id, name and price etc.
  2. Comparable affects the original class i.e. actual class is modified. Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects. Where as Comparator doesn't affect the original class i.e. actual class is not modified. Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted.
  3. Comparable provides compareTo() method to sort elements. Comparator provides compare() method to sort elements.
  4. Comparable is found in java.lang package. Comparator is found in java.util package.
  5. We can sort the list elements of Comparable type by Collections.sort(List) method. We can sort the list elements of Comparator type by Collections.sort(List,Comparator) method.
  6. If you are using Comparable then Class whose objects to be sorted must implement this interface. In Comparator, the class whose objects to be sorted do not need to implement this interface. Some other class can implement this interface. 
ALSO CHECKCore Java Interview Questions And Answers

-K Himaanshu Shuklaa..

No comments:

Post a Comment