9. Object Ordering - Comparable Interface

A List l may be sorted as follows.

Collections.sort(l);

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:

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

The compareTo method compares the receiving object with the specified object and returns:

If the specified object cannot be compared to the receiving object, the method throws a ClassCastException.