"apple", "orange", "plum".

compareTo() could be used to make the same arrangement.

Comparable Interface

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. The 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 obj.

In the above, "T" stands for the type of the objects. For example, if the objects are Strings, then "T" is String.

If some objects are instances of a class that implements Comparable, then each object is less than, equal, or greater than any object of that class. compareTo() returns an integer to show which of these three relations hold.

  Relation   objectA.compareTo( objectB )
objectA Less Than objectB Negative Integer
objectA Equal objectB Zero
objectA Greater Than objectB Positive Integer

For example,

"apple".compareTo("orange") Negative Integer
"apple".compareTo("plum") Negative Integer
"apple".compareTo("apple") Zero
"orange".compareTo("orange") Zero
"orange".compareTo("apple") 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. An 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?

five.compareTo( ten )
ten.compareTo( five )
five.compareTo( five )
ten.compareTo( fifteen )
minusFive.compareTo( ten )
minusFive.compareTo( minusTen )

Hint: for numbers, mentally replace "compareTo" with subtraction and do the arithmetic. For example, five.compareTo( ten ) works like five-ten.