Tuesday, 16 August 2016

Comparable vs Comparator in Java

This is a frequently asked question in many Java interviews from junior to mid level interviews. 


Comparable and Comparator are two very important interfaces provides by java API to sort Array or Collection of objects. The main difference between these two interfaces is that Comparable is used to do the natural sorting while Comparator is used to sort the collection on basis of different attributes of the object.

Comparable - Comparable interface is used to do natural sorting of objects in Collection or Array. In comparable implementation,  class itself needs to implement the Comparable interface and overrides the  compareTo(Object obj) method of Comparable interface. 

Lets understand with an example - we have a Person class (attributes - name, age and email) and we want to sort Persons collection always by name. In this case we can implement Comparable interface on Person class and override compareTo(Object obj) like below.

        @Override
       public int compareTo(Person person) {
             return name.compareTo(person.getName());
      }

Now if we use Collections.sort(personList), it will always sort the collection on the basis of name. That's why its also called natural sorting.

Comparator - Comparator interface is used when we want to sort the collection of objects on the basis of different attributes of the class or sometimes if we are using a predefined class and than we want to sort collection of this class. In above discussed example if we want to sort the collection of Person on the basis of age or email, than we can use comparator interface. 

To implement comparator interface we don't need to modify the existing class. We will create a new class and implement Comparator interface on it. We will override compare(Object obj1, Object obj2) method which compares to given objects.

   class AgeComparater implements Comparator<Person> {
     @Override
     public int compare(Person person1, Person person2) {
                 return person1.getName().compareTo(person2.getName());
       }
    }

Now we use Collections.sort(personList, new AgeComparator()) to sort the collection, it will sort the collection on the basis of Person's age. In the same way we can create other comparators for other attributes of the class.


_________________________________________________
***********************Keep studying***********************

No comments:

Post a Comment