我有一个三类:1.class 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);
}
}
根据这篇文章Java - Syntax Question: What is 我应该这样写:public static <T extends Comparable<? super T>> T max(Collection<? extends T> coll)
.但它现在工作正常。为什么?类 Apple
不执行 Comparable<Apple>
并且没有 super
.
[更新]
Java 泛型和集合书说:
Without the
super
wildcard, finding the maximum of aList<Apple>
would be illegal, even though finding the maximum of aList<Fruit>
is permitted.
最佳答案
假设我们更改了 max
方法:
<T extends Comparable<T>> T max(Collection<? extends T> coll)
您将无法获得 max
的 List<Apple>
因为Apple
不执行 Comparable<Apple>
, 它实现了 Comparable<Fruit>
.但是你我都非常清楚 Apple
知道如何将自己与另一个人进行比较Fruit
因为它继承了该功能。
我们通过更改 max
的声明来解决这个问题对此:
<T extends Comparable<? super T>> T max(Collection<? extends T> coll)
这意味着我们接受任何类 T
这样:
-
T implements Comparable<T>
、或... -
T implements Comparable<X>
对于一些X
这样X
是T
的父类(super class)
为了找到max
,我们必须确保 T
的任何实例可以安全地接受 T
的另一个实例作为其 compare
的参数方法。
在第一种情况下,很明显 T
的任何实例可以安全地接受 T
的另一个实例作为其 compare(T)
的参数方法。
在第二种情况下,T
的任何实例可以安全地接受 T
的另一个实例作为其 compare(X)
的参数方法,因为 T
的所有实例也是 X
的实例.
您的示例说明了第二种情况,其中 T
对应Apple
和 X
对应Fruit
.
关于java - <T extends Comparable< 有问题吗? super T>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6704085/