Tuesday 3 June 2014

Difference between Comparable and Comparator Interface in Java

             This is the one of the most important question one should  know while giving collection interview question . Comparable and the Comparator interfaces, which are the most used in Java as sorting tools for the Collection classes such as the ArrayList, HashSet etc.

     Difference between Comparable and Comparator:-


1) Comparator interface is in java.util package, which implies it's a utility class, while Comparable interface is kept on java.lang package, which means it's essential for Java objects.

2) In comparable ,Only one sort sequence can be created while in Comparator many sort sequences can be created.

3) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

4) If you see then logical difference between these two is Comparator in Java compare two objects provided to it , while Comparable interface compares "this" reference with the object specified. .

5) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implements Comparable interface.Its always good practice to override compareTo() for value objects.

6) If any class implement Comparable interface in Java then collection of that object either list or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.

7) Objects which implement Comparable in Java can be used as keys in a SortedMap like treemap or elements in a SortedSet for example TreeSet, without specifying any Comparator.

 When to use Comparable & When to use Comparator interface:-


    If you want to sort objects based on natural order then use Comparable in Java and if you want to sort on some other attribute of object then use Comparator in Java.

   Sample Example of Comparable & Comparator interface:--


          Let us see coding example to see real implementation of these interfaces. This example will help you to understand it more clearly 

   package com.adnjavainterview;
   import java.util.ArrayList;
   import java.util.Collections;
   import java.util.Comparator;
   import java.util.List;


   public class Employee implements Comparable<Employee> {

          private final String name;
          private int age;
          private int salary;

          public Employee(String name, int age, int salary) {
              this.name = name;
              this.age = age;
              this.salary = salary;
          }

          public int compareTo(Employee employee) {
                  return salary - employee.salary;
          }

          public static class EmployeeAgeComparator implements Comparator<Employee> {

                    public int compare(Employee emp1, Employee emp2) {
                             return emp1.age - emp2.age;
                   }

           }

           public String getName() {
                   return name;
           }

           public int getAge() {
                   return age;
           }

           public int getSalary() {
                   return salary;
           }

           @Override
           public String toString() {
                   return format("Name: {0} AGE: {1} SALARY : {2}", name, age, salary);
           }

           public static void main(String[] args) {
                  List<Employee> employeeList = new ArrayList<Employee>();
                  employeeList.add(new Employee("Mahesh", 26, 10000)); 
                  employeeList.add(new Employee("Satish", 35, 5000));
                  employeeList.add(new Employee("Anil", 41, 6500));
                  employeeList.add(new Employee("Hanamant", 44, 4000));

                  System.out.println("******Before Sorting******");
                  printEmployees(employeeList);

                  System.out.println("******After Comparable Sorting On Salary******");
                  Collections.sort(employeeList);
                  printEmployees(employeeList);

                  System.out.println("******After Comparator Sorting On Age******");
                  Collections.sort(employeeList, new Employee.EmployeeAgeComparator());
                  printEmployees(employeeList);

          }

          private static void printEmployees(List<Employee> employeeList) {
                 for (Employee employee : employeeList) {
                        System.out.println(employee);
                }
        }
  }

  OUTPUT:--

******Before Sorting******
Name: Mahesh AGE: 26 SALARY: 10,000
Name: Satish AGE: 35 SALARY: 5,000
Name: Anil AGE: 41 SALARY: 6,500
Name: Hanamant AGE: 44 SALARY: 4,000

******After Comparable Sorting On Salary****** 

Name: Hanamant AGE: 44 SALARY: 4,000   
Name: Satish AGE: 35 SALARY: 5,000  
Name: Anil AGE: 41 SALARY: 6,500
Name: Mahesh AGE: 26 SALARY: 10,000

******After Comparator Sorting On Age****** 

Name: Mahesh AGE: 26 SALARY: 10,000 
Name: Satish AGE: 35 SALARY: 5,000 
 Name: Anil AGE: 41 SALARY: 6,500
Name: Hanamant AGE: 44 SALARY: 4,000



Related Posts:--
1) String Interview Questions and Answers
2) What is the difference between SendRedirect() and Forward()?
3) Exception Handling Interview questions and answers
4) Difference between final,finalize and finally
5) Factory Design Pattern in Java

No comments:

Post a Comment