"apple", "orange", "plum".
compareTo() could be used to make the same arrangement.
In general, an interface consists of constants and method declarations.
A class that implements an interface must implement each
of the methods listed in the interface.
Comparable interface consists of just one method:
int compareTo( T obj ) // Compare this object with
obj. // Return a negative integer, zero, or a postive integer, // when this object is less than, equal, or greater than
In the above, "T" stands for the type of the objects.
For example, if the objects are
Strings, then "T" is
If some objects are instances of a class that implements
then each object is less than, equal, or greater than
any object of that class.
returns an integer to show which of these three relations hold.
|Relation||objectA.compareTo( objectB )|
|objectA||Less Than||objectB||Negative Integer|
|objectA||Greater Than||objectB||Positive Integer|
Only the sign of the returned integer matters if the return value is not zero. The magnitude of a returned integer does not signify anything.
Examine the following declarations.
They use the wrapper class
Integer discussed at the end of chapter 9C.
Integer object holds an integer as its data, plus provides
several useful methods (such as
compareTo) for working with integers
Integer minusTen = new Integer( -10 ); Integer minusFive = new Integer( -5 ); Integer five = new Integer( 5 ); Integer ten = new Integer( 10 ); Integer fifteen = new Integer( 15 );
What is the result of each of the following?
Hint: for numbers, mentally replace "compareTo" with subtraction and do the arithmetic.
five.compareTo( ten )