1
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"?

urajah
  • 193
  • 2
  • 7
  • possible duplicate of [Java Strings: compareTo() vs. equals()](http://stackoverflow.com/questions/1551235/java-strings-compareto-vs-equals) – MickJ Aug 04 '15 at 16:17

2 Answers2

1
  • 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.
Mena
  • 47,782
  • 11
  • 87
  • 106
0

The equals and compareTo don't influence each other in this code. The compareTo method is determining which element is returned as max, and then the code checks if that element is equal to a2.

In other words, it's checking if a2 is the largest apple, because the comparison made by compareTo checks only for size.

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

size is a field in the Fruit class. In compareTo, both this and that are instances of Fruit, and therefore, both of them have a size field.

Chthonic Project
  • 8,216
  • 1
  • 43
  • 92