【发布时间】:2015-08-04 15:56:51
【问题描述】:
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);
}
}
这个程序中equals()和compareTo()方法的关系是什么?
我知道当类 Fruit 实现接口 Comparable 时,它的主体定义中必须包含 compareTo 方法,但我不明白这个方法对调用 Collections.max(apples).equals(a2) 有什么影响。
compareTo 从哪里获取“that.size”的值?
【问题讨论】:
标签: java equals comparable compareto