"Java Effective" 重写示例中泛型方法的绑定不匹配
Bound mismatch for generic method from "Java Effective" example rewritten
class Main {
public static void main(String[] args) {
List<Sub> list = new ArrayList<Sub>();
Sub r = max(list);
System.out.println(r);
}
static <T extends Comparable<? super T>> T max(List<? extends T> list) {
return null;
}
private static class Super {
}
private static class Sub implements Comparable<Super> {
public int compareTo(Super o) {
return 0;
}
}
}
谁能告诉我为什么我在第 "Sub r = max(list)" 行遇到编译器错误?
我正在阅读 Java 有效的书,正如他们所说,我读到了那本书中最复杂的方法声明。
其实就是那个max方法。
错误是:
Bound mismatch: "The generic method max(List< ? extends T>) of type Main is not applicable for the arguments (List< Main.Sub>). The inferred type Main.Sub is not a valid substitute for the bounded parameter < T extends Comparable< ? super T>>"
您的 Sub
class 必须延长 Super
:
private static class Sub extends Super implements Comparable<Super> {
class Main {
public static void main(String[] args) {
List<Sub> list = new ArrayList<Sub>();
Sub r = max(list);
System.out.println(r);
}
static <T extends Comparable<? super T>> T max(List<? extends T> list) {
return null;
}
private static class Super {
}
private static class Sub implements Comparable<Super> {
public int compareTo(Super o) {
return 0;
}
}
}
谁能告诉我为什么我在第 "Sub r = max(list)" 行遇到编译器错误?
我正在阅读 Java 有效的书,正如他们所说,我读到了那本书中最复杂的方法声明。 其实就是那个max方法。
错误是:
Bound mismatch: "The generic method max(List< ? extends T>) of type Main is not applicable for the arguments (List< Main.Sub>). The inferred type Main.Sub is not a valid substitute for the bounded parameter < T extends Comparable< ? super T>>"
您的 Sub
class 必须延长 Super
:
private static class Sub extends Super implements Comparable<Super> {