绑定不匹配:通用类(扩展Comparable的Generic类(扩展Comparable的Generic类))

Vik*_*oel 0 java generics comparable

我知道这听起来很混乱,但这是我能解释的最好的.(你可以建议一个更好的标题).我有3个班: -

A

public class A <T extends Comparable<T>> {
    ...
}
Run Code Online (Sandbox Code Playgroud)

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>
    ...
}
Run Code Online (Sandbox Code Playgroud)

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);
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

我正在那里我尝试实例化一个错误AB

绑定不匹配:类型C不是有界参数的有效替代<T extends A类型的可比较<T>>

Vik*_*oel 5

感谢@Boris the Spider上面的评论

问题是这C是一种原始类型B .更改实例化以包含参数(根据需要)

A< C<Integer> > var = new A< C<Integer> >();
Run Code Online (Sandbox Code Playgroud)

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

public int compareTo(C<T> o) {
    return t.compareTo(o.t);
}
Run Code Online (Sandbox Code Playgroud)

编辑2:此外,问题中有一个拼写错误(下面的评论)

public class C <T extends Comparable<T>> implements Comparable< C<T> >{...}
Run Code Online (Sandbox Code Playgroud)

  • 你也在`C`中使用原始类型`C`. (2认同)
  • 你使用原始类型`C`的另一个地方是`public class C <T extends Comparable <T >>实现Comparable <C>`.它应该是`public class C <T extends Comparable <T >>实现Comparable <C <T >>`.如果你使用原始类型,可能会发生一些非常奇怪的事情,所以不惜一切代价避免它们. (2认同)