The need to provide compareTo
If a class is for a type
where there is a natural order for the values,
you ought to provide a method
out whether one value is less than another.
Unfortunately, few books on Java teach this.
Some parts of the Collections API
(e.g., TreeSet and TreeMap)
work better if your class implements
the Comparable interface.
This interface is simply:
public interface Comparable
public int compareTo(Object pObject);
To implement Comparable,
Date can be changed to:
public class Date implements Comparable
public int compareTo(final Object pObject)
final Date tDate = (Date)pObject;
int tResult = iYear - tDate.iYear;
tResult = iMonth - tDate.iMonth;
tResult = iDay - tDate.iDay;
Comparable became part of Java
when the Java 2 platform was released in December 1998.
If a class implements
objects of the class can be stored in a
final Set tOccurrences = new TreeSet():