我想定义一个实现通用Comparable接口的类。而在我的类中,我还定义了一个泛型元素T
。为了实现该接口,我将比较委托给了T
。以下是我的代码:
public class Item<T extends Comparable<T>> implements Comparable<Item> {
private int s;
private T t;
public T getT() {
return t;
}
@Override
public int compareTo(Item o) {
return getT().compareTo(o.getT());
}
}
当我尝试编译它时,我收到以下错误信息:
Item.java:11: error: method compareTo in interface Comparable<T#2> cannot be applied to given types;
return getT().compareTo(o.getT());
^
required: T#1
found: Comparable
reason: actual argument Comparable cannot be converted to T#1 by method invocation conversion
where T#1,T#2 are type-variables:
T#1 extends Comparable<T#1> declared in class Item
T#2 extends Object declared in interface Comparable
1 error
有人能告诉我为什么出现这种情况以及如何修复吗?
compareTo(Item o)
更改为compareTo(Item<T> o)
,对吗? - npinti<T extends Comparable<? super T>>
。这个代码片段的含义是限制类型参数T
必须是可比较的,并且可以与其父类进行比较。 - newacct