Search code examples
javaequalscomparablecompareto

Relationship between equals and compareTo methods


public abstract class Fruit implements Comparable<Fruit> {

   protected String name;
   protected int size;
   protected Fruit(String name, int size){
      this.name = name;
      this.size = size;
   }
   public int compareTo(Fruit that){
       return  this.size < that.size ? - 1:
       this.size == that.size ? 0 : 1;
   }
}
class Apple extends Fruit {
   public Apple(int size){ super("Apple",size);
}
public class Test {

   public static void main(String[] args) {

      Apple a1 = new Apple(1); Apple a2 = new Apple(2);

      List<Apple> apples = Arrays.asList(a1,a2);
      assert Collections.max(apples).equals(a2);
   }
}

What is relationship between equals() and compareTo() methods in this program?

I know that when class Fruit implements interface Comparable it must contains in its body definition of compareTo method but I don't understand what influence has this method on calling of: Collections.max(apples).equals(a2).

And from where compareTo takes the value of "that.size"?


Solution

    • Your compareTo method compares Fruits based on their size. This is a custom implementation.
    • Collections.max will invoke compareTo a number of times related to the size of your collection, to infer the max item in the collection, hence compareTo is invoked.
    • Object#equals will be invoked when invoking equals in your example, as it is not overridden in Fruit.
    • The equality will be tested between the "largest" fruit in your collection, and the second Apple you declared, i.e. between the same Apple with size 2 in this case. It should return true.