Saturday, September 29, 2012

Comparator Example


When will you use Comparator and Comparable interfaces?
-java.util.Comparator and java.lang.Comparable
java.util.Comparator compares some other class’s instances, while java.lang.Comparable compares itself with another object.

Comparator vs Comparable in Java

Here are some of the common differences, which is worth remembering to answer this question if asked during a telephonic or face to face interview:

1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package, which very much says that Comparator should be used as an utility to sort objects which Comparable should be provided by default.

2) 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.

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

4) 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.

5) 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.

6)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.

public class Person implements Comparable {
    private int person_id;
    private String name;
   
    /**
     * Compare current person with specified person
     * return zero if person_id for both person is same
     * return negative if current person_id is less than specified one
     * return positive if specified person_id is greater than specified one
     */
    @Override
    public int compareTo(Object o) {
        Person p = (Person) o;
        return this.person_id - o.person_id ;
    }
    ….
}


/**
 * Comparator implementation which sorts Person objects on person_id field
 */
public class SortByPerson_ID implements Comparator{

    public int compare(Object o1, Object o2) {
        Person p1 = (Person) o;
        Person p2 = (Person) o;
        return p1.getPersonId() - p2.getPersonId();
    }
}


Use Collection.sort to sort custom class and user defined comparator

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

@SuppressWarnings("rawtypes")
class employee implements Comparable {
    private String name;
    private Double salary;
   
    public employee(String name, Double salary) {
        super();
        this.name = name;
        this.salary = salary;
    }

    public String getName() {
        return name;
    }

    public Double getSalary() {
        return salary;
    }

    public String toString(){
        return "Name = "+getName()+", Salary = "+getSalary();
    }

    @Override
    public int compareTo(Object o) {
        if(!(o instanceof employee))
            throw new ClassCastException();
       
        employee e = (employee)o;
        return name.compareTo(e.getName());
    }
   
    static class SalaryComparator implements Comparator {
        @Override
        public int compare(Object o1, Object o2) {
            if(! (o1 instanceof employee) || !(o2 instanceof employee))
                throw new ClassCastException();
           
            employee e1 = (employee) o1;
            employee e2 = (employee) o2;
            return (int) (e1.getSalary() - e2.getSalary());
        }       
    }     
}

public class collectionUtil {

    /**
     * @param args
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    public static void main(String[] args) {
        String[] names = { "A", "E", "C", "B", "D" };
        Double[] salaries = { 2.0, 5.0, 6.0, 4.0, 3.0 };
       
        List l = new ArrayList();

        for (int i=0; i < names.length; i++)
            l.add(new employee(names[i], salaries[i]));
       
        Collections.sort(l);
        ListIterator litre = l.listIterator();
        while (litre.hasNext()) {
            //Object object = (//Object) litre.next();
            System.out.println(litre.next());
        }
       
        System.out.println("============================");
       
        Collections.sort(l, new employee.SalaryComparator());
        litre = l.listIterator();
        while (litre.hasNext()) {
            //Object object = (//Object) litre.next();
            System.out.println(litre.next());
        }
       
    }

}

No comments:

Post a Comment