Comparable Interface

Objects that have an ordering are compared using the compareTo() method.

4. Integer


Good Dog


Examine the following declarations. They use the wrapper class Integer. An Integer object holds an integer as its data and provides several useful methods for working with integers. Class Integer implements the Comparable<Integer> interface so two Integers can be compared.

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 );

Mentally replace "compareTo" with subtraction and do the arithmetic. For example, five.compareTo( ten ) works like five-ten. (But recall that is only the sign of the result that matters.)

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 )

Question 4:

Examine the following:

    Integer five = 5 ; Integer ten = 10 ;

What is the value of:

    five.compareTo( ten )