Thursday, 17 July 2008

Difference between a comparator and comparable

If the List consists of String elements, it will be sorted into alphabetical order. If it consists of Date elements, it will be sorted into chronological order.

How does this happen?

String and Date both implement the Comparable interface. Comparable implementations provide a natural ordering for a class, which allows objects of that class to be sorted automatically

If you try to sort a collection (yourCollection), the elements of which do not implement Comparable, Collections.sort(yourCollection) will throw a ClassCastException.

Writing Your Own Comparable Types
The Comparable interface consists of the following method.

public interface Comparable {
public int compareTo(T o);
}

The compareTo method compares the receiving object with the specified object and returns a negative integer, 0, or a positive integer depending on whether the receiving object is less than, equal to, or greater than the specified object.

Now Any collection which maintains the natural ordering like TreeMap, TreeSet would automaticaly sort the entries on the logic of compareTo method. For others cases you would just call the Collection.sort(Collection col) on your collection whenever you want the entries to be sorted on natural order.

Comparators

What if you want to sort some objects in an order other than their natural ordering? Or what if you want to sort some objects that don't implement Comparable?
e.g. naturally String sort the collection in dictionary order. What is you want the sorting to be just opposite of it ?
you'll need to provide a Comparator in such cases — an object that encapsulates an ordering.

Like the Comparable interface, the Comparator interface consists of a single method.

public interface Comparator {
int compare(T o1, T o2);
}

The implementation symantics are same to Comparable.

import java.util.*;

public class ReverseSort {
static final Comparator REVERSE_ORDER =
new Comparator() {
public int compare(String e1, String e2) {
return e2.compareTo(e1.hireDate()); //reverse comparison
}
};

static final Collection names = ... ;

public static void main(String[] args) {
List e = new ArrayList(names);
Collections.sort(e); //This would sort the names in Natural Order ... Dictionary order ...
System.out.println(e);

System.out.println("");
System.out.println("Reverse Order ...");
Collections.sort(e, REVERSE_ORDER);
System.out.println(e);
}
}


0 comments: