Comparable Interface
Objects that have an ordering are compared using the compareTo() method.
7. Consistency with equals()
Answer:
For most classes that implement both methods this is true. But it is possible that it is
not true, so check the documentation.
The compareTo()
method might look only at some instance variables of an
object and ignore others. The equals()
method might look at different instance variables.
Consistency with equals()
equals()
compareTo()
.Here is a program that tests some of these ideas:
class TestCompareTo { public static void main ( String[] args ) { String appleA = new String("apple"); // these are two distinct objects String appleB = new String("apple"); // these are two distinct objects String berry = new String("berry"); String cherry = new String("cherry"); String A, B; A = appleA; B = appleB; System.out.print( A + ".compareTo(" + B + ") returns "); if ( A.compareTo(B) == 0) System.out.println("Zero"); if ( A.compareTo(B) < 0 ) System.out.println("Negative"); if ( A.compareTo(B) > 0 ) System.out.println("Positive"); System.out.println( A + ".equals(" + B + ") is " + A.equals(B) ); System.out.println(); A = appleA; B = berry; System.out.print( A + ".compareTo(" + B + ") returns "); if ( A.compareTo(B) == 0) System.out.println("Zero"); if ( A.compareTo(B) < 0 ) System.out.println("Negative"); if ( A.compareTo(B) > 0 ) System.out.println("Positive"); System.out.println( A + ".equals(" + B + ") is " + A.equals(B) ); System.out.println(); A = berry; B = appleA; System.out.print( A + ".compareTo(" + B + ") returns "); if ( A.compareTo(B) == 0) System.out.println("Zero"); if ( A.compareTo(B) < 0 ) System.out.println("Negative"); if ( A.compareTo(B) > 0 ) System.out.println("Positive"); System.out.println( A + ".equals(" + B + ") is " + A.equals(B) ); } } |
Here is the output of the program. You might want to copy the program to a file and run it with a few more selections for A
and B
.
apple.compareTo(apple) returns Zero
apple.equals(apple) is true
apple.compareTo(berry) returns Negative
apple.equals(berry) is false
berry.compareTo(apple) returns Positive
berry.equals(apple) is false
If you edit the program and change some of the strings to contain upper case, the program might output mysterious results.
Question 7:
(Thought Question: ) Do you think that "APPLE".compareTo("apple")
returns zero?