Say that X.compareTo(Y)==0
.
Is it then true that X.equals(Y)
?
For most classes that implement both methods this is true. But it is possible that it is not true, so check the documentation.
equals()
If you are defining a class and writing its methods, you should probably
make sure that this rule (and the previous rules) hold true.
But for some classes, there might be several possible ideas of what "equals"
means, and the idea picked might not not be consistent with compareTo()
.
Here is a program that tests some of these ideas:
class TestCompareTo { public static void main ( String[] args ) { String appleA = new String("apple"); // want distinct objects, not literals String appleB = new String("apple"); String berry = "berry"; String cherry = "cherry"; String damson = "damson"; String A, B; A = appleA; B = appleB; System.out.println(); 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) ); A = appleA; B = berry; System.out.println(); 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) ); A = berry; B = appleA; System.out.println(); 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.
(Thought Question: ) Do you think that "APPLE".compareTo("apple")
returns zero?