Java Reference
In-Depth Information
The Comparable Interface
The Comparable interface is in the java.lang package and so is automatically available to
your program. The Comparable interface has only the following method heading that must
be given a definition for a class to implement the Comparable interface:
public int compareTo(Object other);
The method compareTo should return
a negative number if the calling object “comes before” the parameter other ,
a zero if the calling object “equals” the parameter other ,
and a positive number if the calling object “comes after” the parameter other .
The “comes before” ordering that underlies compareTo should be a total ordering. Most nor-
mal ordering, such as less-than ordering on numbers and lexicographic ordering on strings,
are total ordering.
If you define a class that implements the Comparable interface but that does not satisfy
these conditions, then code written for Comparable objects will not work properly. It is the
responsibility of you the programmer to ensure that the semantics is satisfied. Neither the
compiler nor the run-time system enforces any semantics on the Comparable interface.
If you have read this subsection, you should also read the following Programming
Example.
EXAMPLE: Using the Comparable Interface
Display 13.5 shows a class with a method that can sort any partially filled array whose base
type implements the Comparable interface (including implementing the semantics we dis-
cussed in the previous subsection). To obtain the code in Display 13.5, we started with the
sorting code in Display 6.11 and mechanically replaced all occurrences of the array type
double[] with the type Comparable[] . We replaced all Boolean expressions of the form
Expression_1 < Expression_2
with
Expression_1 .compareTo( Expression_2 ) < 0
We also changed the comments a bit to make them consistent with the compareTo
notation. The changes are highlighted in Display 13.5. Only four small changes to the
code were needed.
(continued on page 704)
Search WWH ::




Custom Search