我有三个类:1. Algorithm
类,其中 max()
方法可以在 Collection
中查找最大值:
public class Algorithm {
public static <T extends Comparable<T>> T max(Collection<? extends T> coll) {
T max = coll.iterator().next();
for (T elm : coll) {
if (max.compareTo(elm) < 0)
max = elm;
}
return max;
}
}
2.类 Fruit
:
public class Fruit implements Comparable<Fruit> {
private String name;
private int size;
public Fruit(String name, int size) {
this.name = name;
this.size = size;
}
public int compareTo(Fruit that) {
if (size < that.size)
return -1;
else if (size == that.size)
return 0;
else
return 1;
}
}
3. 类 Apple
继承自 Fruit
:
public class Apple extends Fruit {
public Apple(int size) {
super("Apple", size);
}
}
现在的问题是:
public class Main
{
public static void main(String[] args) {
Apple a1 = new Apple(10);
Apple a2 = new Apple(34);
List<Apple> apples = Arrays.<Apple>asList(a1, a2);
System.out.println(Collections.max(apples).size);
}
}
根据这篇文章,我应该这样写:
public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll)
。但是现在它正常工作了。为什么?类Apple
没有实现Comparable<Apple>
,也没有使用super
。[更新]
Java泛型和集合书中说:
如果没有使用
super
通配符,查找List<Apple>
的最大值将是非法的,即使查找List<Fruit>
的最大值是允许的。
Ints
类有一个compare(int, int)
方法,使得int
比较更加容易。 - Adam PaynterInteger
类现在提供了相同的方法。 - Matt Ball