next up previous index
Next: Binary Search Trees Up: Generic methods Previous: The Comparable Interface   Index

Doing it yourself

You may wish to implement your own compareTo method for a particular class. In that case there are certain algebraic conditions that you must ensure, namely that

  1. $\;
{\rm sign} (\verb*+x.compareTo(y)+) =
-{\rm sign} (\verb*+y.compareTo(x)+)$
  2. $\;
\verb*+x.compareTo(y)+ < 0 \; \mbox{and}\; 
\verb*+y.compareTo(z)+ < 0 \;\mbox{imply}\;
\verb*+x.compareTo(z)+ < 0$
  3. $\;
\verb*+x.compareTo(y)+ = 0 \; \mbox{implies}\; 
{\rm sign} (\verb*+x.compareTo(z)+) =
{\rm sign} (\verb*+y.compareTo(z)+)$
The first requires that x.compareTo(y) is positive if and only if y.compareTo(x) is negative, and conversely, and that if either is 0 so is the other. The second implies that the order relation is transitive: ${\tt x}<{\tt y}$ and ${\tt y}<{\tt z}$ implies ${\tt x}<{\tt z}$. The third says that if x and y are ``equal'' in the ordering, they should compare in the same way with any other object in the domain.

It is not required that to be equal in the ordering two objects should in fact be equal. Nonetheless the jdk reommends that x.compareTo(y) should have the value $0$ if and only if x.equals(y) is true. An implementation which violates this condition is encouraged to give a clear indication of the fact by saying

  Note: this class has a natural ordering that is inconsistent with equals.
Equality of two objects should imply that they are equal in the ordering. But do not be inhibited from using an ordering in which distinct objects may be equal in the ordering, if it serves a useful purpose.


next up previous index
Next: Binary Search Trees Up: Generic methods Previous: The Comparable Interface   Index
Peter Williams 2005-06-07