## 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()

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"); // 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 Zeroapple.equals(apple) is trueapple.compareTo(berry) returns Negativeapple.equals(berry) is falseberry.compareTo(apple) returns Positiveberry.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?