• One of the common interview question What are the differences between comparable and comparator and how to sort collections using these interfaces ?
  • What are the differences between comparable and comparator and how to sort employee object by empId or empName using these interfaces.
  • In this topic we will clear questions like difference between comparable and comparator in java, comparator vs comparable in java with example and comparable and comparator in java
  • Comparator and Comparable are two interfaces in Java API.
  • Before discussing about differences lets see brief description about these two interfaces

Comparable Interface:

  • Comparable Interface is actually from java.lang package.
  • It will have a method compareTo(Object obj)to sort objects
  • public int compareTo(Object obj){ }
  • Comparable interface used for natural sorting these is the reason all wrapper classes and string class implementing this comparator and overriding compareTo(Object obj) method.
  • So in String and all wrapper classes compareTo(Object  obj) method is implemented in such way that it will sort all objects.

String class:

  • If we observe String class it is implementing comparable interface.
  • If compareTo(String str) methods returns 0 : both strings are equal
  • If compareTo(String str) method returns 1: string is lexicographically greater than the string argument
  • If compareTo(String str) method returns -1: string is lexicographically less than the string argument

  1. package java.lang;
  2.  
  3. public final class String
  4. extends Object
  5. implements Serializable, Comparable<String>, CharSequence {
  6.   
  7. public int compareTo(String anotherString){
  8.  //logic
  9. }
  10. }

Comparing String Objects:

  •  Lets see an example java program that will explains how two string objects are compared using compareTo(String str) method in String class.


  1. package com.instanceofjava;
  2. public class StringCompareDemo {
  3. public static void main(String [] args){
  4.    
  5.  String str1="comparable";
  6.  String str2="comparator";
  7.  
  8. int value=str1.compareTo(str2);
  9.  
  10. if(value==0){
  11.  
  12. System.out.println("Strings are equal");
  13.  
  14. }
  15. else{
  16.  
  17. System.out.println("Strings are not equal");
  18.  
  19. }
  20.  
  21. }
  22. }

Output:

  1. Strings are not equal

Wrapper classes:

  • Wrapper classes is used to convert primitive data values into java objects. for 8 primitive data types java has 8 corresponding wrapper classes. All these classes implementing comparable interface.
  • Lets see an example on Integer wrapper class 

Integer:


  1. package java.lang;
  2. public final class Integer
  3. extends Number
  4. implements Comparable<Integer> {
  5.   
  6. public int compareTo(Integer i){
  7.  //
  8. }
  9. }

  •  Lets see an example program of comparing two integer objects

  1. package instanceofjava;
  2.  
  3. public class IntegerComparableDemo {
  4.  
  5. public static void main(String [] args){
  6.  
  7.    // compares two Integer objects numerically
  8.  
  9.    Integer obj1 = new Integer("37");
  10.    Integer obj2 = new Integer("37");
  11.  
  12.    int retval =  obj1.compareTo(obj2);
  13.  
  14. if(retval > 0) {
  15.  
  16.    System.out.println("obj1 is greater than obj2");
  17. }
  18.  
  19. else if(retval < 0) {
  20.  
  21.  System.out.println("obj1 is less than obj2");
  22.  
  23.  }
  24.  else {
  25.  
  26.  System.out.println("obj1 is equal to obj2");
  27.  
  28. }
  29.  
  30. }

Output:
  1. obj1 is equal to obj2;

Sorting Collections using Comparable :

  •  By using Collections.sort(list); method we can sort objects in natural object sorting order 
  • An example program on Collections.sort(list); 
  • Sorting Employee objects by id.



  1. package instanceofjava;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class Employee implements  Comparable {
  8.  
  9.     String name;
  10.     int id;
  11.  
  12.  public String getName() {
  13.         return name;
  14.  }
  15.  
  16.  public void setName(String name) {
  17.         this.name = name;
  18.  }
  19.  
  20. public int getId() {
  21.  
  22.        return id;
  23.  }
  24.  
  25. public void setId(int id) {
  26.         this.id = id;
  27. }
  28.  
  29.  public Employee(String name, int id) {
  30.         this.name=name;
  31.         this.id=id;
  32. }
  33.  
  34.  @Override
  35.  public int compareTo(Object in) {
  36.         return  new Integer(this.id).compareTo(((Employee)in).id);
  37.   }
  38.  public static void main(String[] args) {
  39.  
  40.         Employee e1= new Employee("xyz", 37);
  41.         Employee e2= new Employee("abc", 46);
  42.         Employee e3= new Employee("sai", 38);
  43.  
  44.         ArrayList al= new ArrayList();
  45.  
  46.         al.add(e1);
  47.         al.add(e2);
  48.         al.add(e3);
  49.         Collections.sort(al);
  50.         Iterator itr= al.iterator();
  51.  
  52.      while (itr.hasNext()) {
  53.             Employee em = (Employee) itr.next();
  54.             System.out.println(em.getId()+" "+em.getName());            
  55.        }
  56. }
  57. }
     
Output:

  1. 37 xyz
  2. 38 sai
  3. 46 abc

Comparator:

  • Comparator Interface is actually from java.util package.
  • It will have a method compare(Object obj1, Object obj2)to sort objects
  • public int  compare(Object obj1, Object obj2){ }
  • Comparator interface used for customized sorting.
  • Will place sorting logic in other class so that its easy to change.
  • An example program which will sort employee objects by name

 

 1.Employee.java

  1. package instanceofjava;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class Employee  {
  8.  
  9.     String name;
  10.     int id;
  11.  
  12.  public String getName() {
  13.         return name;
  14.  }
  15.  
  16.  public void setName(String name) {
  17.         this.name = name;
  18.  }
  19.  
  20. public int getId() {
  21.  
  22.        return id;
  23.  }
  24.  
  25. public void setId(int id) {
  26.         this.id = id;
  27. }
  28.  
  29.  public Employee(String name, int id) {
  30.         this.name=name;
  31.         this.id=id;
  32. }
  33.  
  34.  
  35.  public static void main(String[] args) {
  36.  
  37.         Employee e1= new Employee("xyz", 37);
  38.         Employee e2= new Employee("abc", 46);
  39.         Employee e3= new Employee("sai", 38);
  40.  
  41.         ArrayList al= new ArrayList();
  42.  
  43.         al.add(e1);
  44.         al.add(e2);
  45.         al.add(e3);
  46.        Collections.sort(al, new EmpSortByName());
  47.         Iterator itr= al.iterator();
  48.  
  49.      while (itr.hasNext()) {
  50.             Employee em = (Employee) itr.next();
  51.             System.out.println(em.getId()+" "+em.getName());            
  52.        }
  53. }
  54. }

EmpSortByName.java:

 

  1. package instanceofjava;
  2. import java.util.Comparator;
  3. public class EmoSortByName implements Comparator<Employee> {
  4.  
  5.     @Override
  6.     public int compare(Employee arg0, Employee arg1) {
  7.         return arg0.getName().compareTo(arg1.getName());
  8.     }
  9.  
  10. }
     
Output:

  1. 46 abc
  2. 38 sai
  3. 37 xyz

Differences Between Comparable and Comparator:


Parameter Comparable Comparator
Package java.lang.Comparable java.util.Comparator
Sorting logic Must be in Same class Separate class
Method definition public int compareTo(Object obj) public int compare(Object obj1, Object obj2)
Method call Collections.sort(list) Collections.sort(list, new OtherSortClass())
Purpose Natural Sorting Custom Sorting


You Might Like:

1. Java Concept and Example Programs 
2. Java Concept and Interview Questions 
3. Core java Tutorial
4. Java experience interview Questions
5. Java Programs asked in Interviews

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu