«^»
4.2. Using the Comparator interface

If a class such as Date fails to implement the Comparable interface, or its implementation of compareTo provides inappropriate code, a client class can still store Date objects in a TreeSet or a TreeMap provided it creates the TreeSet/TreeMap using a constructor that is passed an object that implements the Comparator interface ([7]). This interface requires the object to provide the method:

public int compare(Object pObject1, Object pObject2);
This method returns a negative integer, zero, or a positive integer depending on whether the value of pObject1 is less than, equal to, or greater than that of pObject2.

If, bizarrely, we chose to compare dates only on the year field, we could provide:

public class MyDateComparator implements java.util.Comparator
{
   public int compare(final Object pObject1, final Object pObject2)
   {
      return ((Date)pObject1).getYear() - ((Date)pObject2).getYear();
   }
}
and then use:
MyDateComparator tMyDateComparator = new MyDateComparator();
final Set tOccurrences = new TreeSet(tMyDateComparator):
tOccurrences.add(tDeathOfBach);