Friday, 19 October 2012

Comparable and Comparator example


 Difference between Comparable and Comparator


[1]. java.lang.Comparable

  
  To implements comparable interface, A class must implement a single method compareTo().

    int obj1.compareTo(obj2)

 
java.util.Comparator

    To implements comparator interface, A class must implement a single method compare().

    int compare (obj1,obj2)

[2] Comparable

If a class implements the java.lang.Comparable interface then it will be able to compare its instances
itself with its another object

Comparator

This class will not compare its instances but it will be able to compare some other class’s instances.
A comparator object is capable of comparing two different objects.

[3]  Comparable interface having public int compareTo(Object o) method  returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Comparator interface having public int compare (Object o1, Object o2) method  returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

// This is the sample program for Comparable interface.

package com.corejava.gaurav.examples;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Collections;


@SuppressWarnings("rawtypes")
public class EmployeeComparableTestExample implements Comparable{
    private int empAge;
    private String empName;
   
    public EmployeeComparableTestExample(int age,String name){
        this.empAge = age;
        this.empName = name;
       
    }

    public int compareTo(Object obj){
        EmployeeComparableTestExample empTest = (EmployeeComparableTestExample)obj;
        int result = 0;
        Integer in1 = new Integer(this.empAge);
        Integer in2 = new Integer(empTest.empAge);
        result = in1.compareTo(in2);
        if(result==0){
            result = this.empName.compareTo(empTest.empName);
        }
        return result;
    }
   
    @SuppressWarnings({"unchecked" })
    public static void main(String args[]){

        List arrayLst = new ArrayList(0);
        arrayLst.add(new EmployeeComparableTestExample(55,"Nayan"));
        arrayLst.add(new EmployeeComparableTestExample(15,"Mihika"));
        arrayLst.add(new EmployeeComparableTestExample(34,"Dhiraj"));
        arrayLst.add(new EmployeeComparableTestExample(55,"Avantika"));
        Collections.sort(arrayLst);
        Iterator itr = arrayLst.iterator();
        while(itr.hasNext()){
            System.out.println(itr.next());
        }
    }
    @Override
    public String toString(){
        return "Employee Age - "+empAge +" And His Name is - "+empName;
    }
   
}


// This is the sample program for Comparator interface.

package com.corejava.gaurav.examples;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class Employee2{
    int empId;
    String empName;
    public Employee2(int id,String name){
        this.empId = id;
        this.empName = name;
    }
   
    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;
    }
    @Override
    public String toString(){
        return "Employee Id is "+ empId +" And Employee Name is "+empName;
    }
}


@SuppressWarnings("rawtypes")
public class EmployeeComparator implements Comparator{
   
    public int compare(Object obj1,Object obj2){
        int result = 0;
        Employee2 emp = (Employee2)obj1;
        Employee2 emp1 = (Employee2)obj2;
       
        Integer int1 = new Integer(emp.getEmpId());
        Integer int2 = new Integer(emp1.getEmpId());
       
        result = int1.compareTo(int2);
       
        if(result == 0){
            result = emp.getEmpName().compareTo(emp1.getEmpName());
       
        }
       
        return result;
    }

    @SuppressWarnings("unchecked")
    public static void main(String args[]){

        List arLst = new ArrayList(0);
        arLst.add(new Employee2(32785,"Gaurav"));
        arLst.add(new Employee2(62653,"Pritish"));
        arLst.add(new Employee2(12345,"Anita"));
        arLst.add(new Employee2(32885,"Bhupesh"));
        Collections.sort(arLst, new EmployeeComparator());
        for(Object obj:arLst){
            System.out.println(obj);
                 }
        }
}

Note:-  In Java Comparable interface is used to implement natural ordering of object. String, Date and wrapper classes implements Comparable interface. Comparator is used for sorting customization.

With the help of comparator we can provide more then one order behavior while this is not true with comparable.

No comments:

Post a Comment