Comparable and Comparator -Part 2



Generic Form of Comparable

With the introduction of Generics in Java SE 5.0, Comparable has been parameterized and their signature has been changed to :

Signature:
    public interface Comparable<T>  and
   
    public int compareTo(T o)


Generic form of Comparable is shown below:

Employee.java

public class Employee implements Comparable<Employee>{

   private int empId;
   private String name;
   private  String city;
   private double salary;

  @Override
  public int compareTo(Employee obj){

    /*Checking whether argument is null or not.*/
      if(obj == null){
        throw new NullPointerException("Object passed is null!");
    }

    /*No need to check ClassCastException as argument passed is already of type Employee and type  checking is done at compile time.*/
    /*
       if(!(obj instanceof Employee)){
         throw new ClassCastException("Not Comparable Objects!");
     }
  */        

  /* Also no need to cast*/
  /*int id = ((Employee)obj).getEmpId(); */
      
    int id = obj.getEmpId();
      
    if(this.getEmpId() < id)  
          return -1;
   else if(this.getEmpId() > id )
        return 1;
   else
       return 0;
}

  public void setEmpId(int id){  
        this.empId=id;
  }
 
 public int getEmpId(){  
        return empId;  
 }
  
 public void setName(String name){  
        this.name=name;
 }
 
  public String getName(){  
        return name;  
  }
  
  public void setCity(String city){  
        this.city=city;
  }
 
  public String getCity(){  
        return city;  
  }

    public void setSalary(double sal){  
        this.salary=sal;
    }
 
  public double getSalary(){  
        return salary;  
    }
}




EmployeeComparision.java

public class EmployeeComparision{
 
    public static void main(String args[]){
     
        /*Creating two Employees */
     
        Employee emp1 = new Employee();      
        emp1.setEmpId(2);
        emp1.setName("Mr. X");
        emp1.setCity("NY");
        emp1.setSalary(25000.0);
       
        Employee emp2 = new Employee();      
        emp2.setEmpId(1);
        emp2.setName("Mr. Y");
        emp2.setCity("New Delhi");
        emp2.setSalary(35000.0);
     
        System.out.println("Employees in acsending order(according to their ids):");
        if(emp1.compareTo(emp2) < 0) {      
            System.out.println("Emp1 < Emp2");
     
        } else if(emp1.compareTo(emp2) > 0) {      
            System.out.println("Emp2 < Emp1");
     
        } else if(emp1.compareTo(emp2) == 0) {      
            System.out.println("Both employees have same Id: emp1==emp2");      
        }
 
    }

}

Output: Emp2 < Emp1

Note that now our class declaration has been changed to:

public class Employee implements Comparable<Employee>{
}

and compareTo() is accepting object of type Employee instead of Object:

public int compareTo(Employee e2){
}

There are two benefits of using generics:

1) No need to put a check for ClassCastException in compareTo()

The type checking of the argument passed to compareTo() will happen at compile time and if an object other than of type Employee is passed to it then it will give an error on compiling. So there is no need to check ClassCastException at runtime.

2) No need to cast

Second thing is that you do not need to cast object passed to compareTo() to Employee as we did earlier in non-generic form.

int id = obj.getEmpId();  // No Casting needed

instead of

int id = ((Employee)obj).getEmpId();

Classes from Java API which implement Comparable interfaces

String, Wrapper classes (like Integer,Character etc), Date, Calendar etc.

Click on Next >> to know how you can use Arrays.sort() and Collections.sort() along with Comparable.




I would like to know your comments and if you liked the article then please share it on social networking buttons.


No comments:

Post a Comment