gpt4 book ai didi

java - 重写 "Java Effective"示例中泛型方法的绑定(bind)不匹配

转载 作者:行者123 更新时间:2023-11-29 03:10:05 26 4
gpt4 key购买 nike

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 Effective 一书,正如他们所说,我读到了那本书中最复杂的方法声明。其实就是那个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 类必须扩展 Super:

private static class Sub extends Super implements Comparable<Super> {

关于java - 重写 "Java Effective"示例中泛型方法的绑定(bind)不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29864416/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com