Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Saturday, 12 October 2013

Difference between Comparator and Comparable in java

In our previous discussions we came across 'What are inner classes in Java' and 'What is anonymous inner class in Java'. In this particular blog we will see 'Difference between Comparator and Comparable in java ' and 'How to sort a collection or array of objects in Java'. This tutorial will walk you through how to use an 'Employee' class object as a key in Collections like hashset, hashmap etc.

Before we come forward to the difference between comparator and comparable, lets us first see the implementation of these two.


Using Comparable interface in Java

In java, if a class implements Comparable interface than a collection of its objects can be sorted using Collection.sort() method and an array of objects containing this class's objects as elements can be sorted using Arrays.sort(). The comparison and sorting is done on the basis of one of the property of the class in a overrriden method of Comparable called 'compareTo(Employee emp)'.

Employee.java - Class to implement Comparable Interface

package com.beingjavaguys.core;

public class Employee implements Comparable<Employee> {

 private int empId;
 private String empName;

 Employee(int empId, String empName) {
  this.empId = empId;
  this.empName = empName;
 }

 @Override
 public int compareTo(Employee emp) {
  return (this.empId < emp.empId) ? -1 : (this.empId > emp.empId) ? 1 : 0;
 }

 public int getEmpId() {
  return empId;
 }

 public void setEmpId(int empId) {
  this.empId = empId;
 }

 public String getEmpName() {
  return empName;
 }

 public void setEmpName(String empName) {
  this.empName = empName;
 }

}


Sorting an collection of java objects using Comparable.

In java, if a class (Employee) implements Comparable interface than a collection of its objects can be sorted using Collection.sort() method. The comparison is done on the basis of one of the property of class (id or name), as implemented in 'compareTo(Employee emp)' overriden method.
package com.beingjavaguys.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class Implementation {
 public static void main(String args[]) {

  Employee employee1 = new Employee(2, "Zinger");
  Employee employee2 = new Employee(4, "Jolly");
  Employee employee3 = new Employee(1, "Sanorita");
  Employee employee4 = new Employee(3, "Andrew");

  ArrayList<Employee> empList = new ArrayList<Employee>();
  empList.add(employee1);
  empList.add(employee2);
  empList.add(employee3);
  empList.add(employee4);

  System.out.println("EmpList elemnets befor sorting by id :");
  for (int i = 0; i < empList.size(); i++) {
   System.out.println("EmpId: " + empList.get(i).getEmpId()
     + " | EmpName: " + empList.get(i).getEmpName());
  }

  Collections.sort(empList);

  System.out.println("EmpList elemnets after sorting by id :");
  for (int i = 0; i < empList.size(); i++) {
   System.out.println("EmpId: " + empList.get(i).getEmpId()
     + " | EmpName: " + empList.get(i).getEmpName());
  }

 }
}


Output:

Elements of ArrayList containing Employee's objects before and after sorting by Id.



Sorting an array of java class objects using Comparable.

In java, if a class (Employee) implements Comparable interface than a array of its objects can be sorted using Arrays.sort() method. The comparison is done on the basis of one of the property of class (id or name), as implemented in 'compareTo(Employee emp)' overriden method.
package com.beingjavaguys.core;

import java.util.Arrays;

public class Implementation {
 public static void main(String args[]) {

  Employee employee1 = new Employee(2, "Zinger");
  Employee employee2 = new Employee(4, "Jolly");
  Employee employee3 = new Employee(1, "Sanorita");
  Employee employee4 = new Employee(3, "Andrew");

  Employee empArray[] = { employee1, employee2, employee3, employee4 };

  System.out.println("EmpArray elemnets befor sorting by id :");
  for (int i = 0; i < empArray.length; i++) {
   System.out.println("EmpId: " + empArray[i].getEmpId()
     + " | EmpName: " + empArray[i].getEmpName());
  }

  Arrays.sort(empArray);

  System.out.println("EmpArray elemnets after sorting by id :");
  for (int i = 0; i < empArray.length; i++) {
   System.out.println("EmpId: " + empArray[i].getEmpId()
     + " | EmpName: " + empArray[i].getEmpName());
  }

 }
}


Output:

Elements of Array containing Employee's objects before and after sorting by Id.



Using an java class's objects as a key in collections.

Further more, Objects of classes (Employee) which implement Comparable interface in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface.
package com.beingjavaguys.core;

import java.util.HashMap;

public class Implementation {
 public static void main(String args[]) {

  Employee employee1 = new Employee(2, "Zinger");

  HashMap<Employee, String> empObjAsKey = new HashMap<Employee, String>();
  empObjAsKey.put(employee1, "Employee 1");

  System.out.println("HashSet value for employee1 as a key: "
    + empObjAsKey.get(employee1));

 }
}



Using Comparator interface in Java

Using Comparator interface, the class itself does not need to implement any interface, rather an other class implements the Comparator interface to sort the collection or array of objects using compare() method.

Employee.java - No need to implement any interface itself

package com.beingjavaguys.core;

public class Employee {

 private int empId;
 private String empName;

 Employee(int empId, String empName) {
  this.empId = empId;
  this.empName = empName;
 }

 public int getEmpId() {
  return empId;
 }

 public void setEmpId(int empId) {
  this.empId = empId;
 }

 public String getEmpName() {
  return empName;
 }

 public void setEmpName(String empName) {
  this.empName = empName;
 }

}



SortEmployeeById .java - Class to implement Comparator Interface

package com.beingjavaguys.core;

import java.util.Comparator;

public class SortEmployeeById implements Comparator<Employee> {

 @Override
 public int compare(Employee emp1, Employee emp2) {

  return (emp1.getEmpId() < emp2.getEmpId()) ? -1
    : (emp1.getEmpId() > emp2.getEmpId()) ? 1 : 0;
 }

}



SortEmployeeByName .java - Class to implement Comparable Interface

package com.beingjavaguys.core;

import java.util.Comparator;

public class SortEmployeeByName implements Comparator<Employee> {

 @Override
 public int compare(Employee emp1, Employee emp2) {
  return (emp1.getEmpName().compareTo(emp2.getEmpName()));  
  
 }

}


Sorting an collection of java objects using Comparator Interface.

We have created an 'Employee' class, this class does not implement any interface. To sort collection or arrays of elements of Employe we have added two new classes. 'SortEmployeeById' and 'SortEmployeeByName' are the classes implementing Comparator interface these classes can be used to sort a collection or array of 'Employee' class object on the basis of 'empId' & 'empName' respectively.
package com.beingjavaguys.core;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class Implementation {
 public static void main(String args[]) {

  Employee employee1 = new Employee(2, "Zinger");
  Employee employee2 = new Employee(4, "Jolly");
  Employee employee3 = new Employee(1, "Sanorita");
  Employee employee4 = new Employee(3, "Andrew");

  ArrayList<Employee> empList = new ArrayList<Employee>();
  empList.add(employee1);
  empList.add(employee2);
  empList.add(employee3);
  empList.add(employee4);

  System.out.println("EmpList elemnets befor sorting :");
  for (int i = 0; i < empList.size(); i++) {
   System.out.println("EmpId: " + empList.get(i).getEmpId()
     + " | EmpName: " + empList.get(i).getEmpName());
  }

  Collections.sort(empList, new SortEmployeeById());

  System.out.println("EmpList elemnets after sorting by id :");
  for (int i = 0; i < empList.size(); i++) {
   System.out.println("EmpId: " + empList.get(i).getEmpId()
     + " | EmpName: " + empList.get(i).getEmpName());
  }

  Collections.sort(empList, new SortEmployeeByName());

  System.out.println("EmpList elemnets after sorting by name :");
  for (int i = 0; i < empList.size(); i++) {
   System.out.println("EmpId: " + empList.get(i).getEmpId()
     + " | EmpName: " + empList.get(i).getEmpName());
  }

 }
}



Output:

Elements of ArrayList containing Employee's objects before and after sorting by Id.



Difference between Comparator and Comparable Interface

1) 'Comparable' resides in java.lang package while 'Comparator' residen in java.util package.
2) Using 'Comparable' interface, sorting logic should be written in the same class that is to be sorted while using 'Comparator' interface sorting logic is written in different class so that different sorting logic can be written on the basis of different attributes of the class.
3) Using 'Comparable' interface, sorting is done based on compareTo(Employee emp) method implementation, while in 'Comparator' interface sorting is done on the basis of compare(emp1, emp2) method.
4) Comparable's compareTo(Employee emp), compares 'this' object with 'emp' and returns an integer value. Returns 1 if (this>emp), -1 if(this<emp) and 0 if(this==emp). Comparator's compare(emp1, emp2), compares 'emp1' object with 'emp2' and returns an integer value. Returns 1 if (emp1>emp2), -1 if(emp1<emp2) and 0 if(emp1==emp2).

Here we are done with Difference between Comparator and Comparable in java example and explanation. In our upcoming blogs we will see more about Java Programming and other opensource technologies.








Thanks for reading !
Being Java Guys Team




7 comments:

  1. wow.............really nice explanation ............... thanks mate...... happy coding................. ;)

    ReplyDelete
  2. Nice Tutorial....:)
    Thanks

    ReplyDelete
  3. good one, very useful

    ReplyDelete
  4. It's nice but keep updated for all tlatest technologies as well

    ReplyDelete
  5. Thank you, this is very good example

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft