java实现泛型Comparable接口问题
我定义了一个类实现Comparable泛型接口,然后在类里面也声明了一个泛型的成员t。在实现Comparable接口的compareTo方法时,我希望使用这个泛型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
问题的原因在哪里呢?还请高手解惑。
------解决方案--------------------一楼的代码
return getT().compareTo(o.getT());
改成
return getT().compareTo((T)o.getT());