gpt4 book ai didi

java - 绑定(bind)不匹配 : Generic class (of a Generic class extending Comparable (of a Generic class extending Comparable))

转载 作者:行者123 更新时间:2023-12-01 16:58:05 28 4
gpt4 key购买 nike

我知道这听起来很困惑,但这是我能解释的最好的了。 (您可以建议一个更好的标题)。我有 3 节课:-

A

public class A <T extends Comparable<T>> {
...
}

B

public class B {
A<C> var = new A<C>();
// Bound mismatch: The type C is not a valid substitute for the bounded parameter <T extends Comparable<T>> of the type A<T>
...
}

C

public class C <T extends Comparable<T>> implements Comparable<C>{
private T t = null;
public C (T t){
this.t = t;
}
@Override
public int compareTo(C o) {
return t.compareTo((T) o.t);
}
...
}

我尝试在 B 中实例化 A 时遇到错误

绑定(bind)不匹配:类型 C 不是类型 A 的有界参数 > 的有效替代

最佳答案

感谢上面@Boris the Spider 的评论

问题是 CB 中的原始类型。更改实例化以包含参数(根据需要)

A< C<Integer> > var = new A< C<Integer> >();

编辑1:另外,感谢下面的评论。更好的做法是将 C 中的compareTo 方法更改为此,

public int compareTo(C<T> o) {
return t.compareTo(o.t);
}

编辑2:另外,问题中有一个拼写错误(w.r.t.下面的评论)

public class C <T extends Comparable<T>> implements Comparable< C<T> >{...}

关于java - 绑定(bind)不匹配 : Generic class (of a Generic class extending Comparable (of a Generic class extending Comparable)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019440/

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