我想定义一个实现通用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());
}
}
Run Code Online (Sandbox Code Playgroud)
当我尝试编译它时,我收到以下错误信息:
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 …Run Code Online (Sandbox Code Playgroud) Java集合接口中存在一些继承关系.例如,Collection<T>接口将扩展Iterable<T>.我检查了JDK中的源代码,基类中定义的一些方法在子类中多次重复.例如:
Interable<T>接口中定义的方法 Iterator<E> iterator();,但在接口Collection<E>和List<T>,也含有相同的方法.根据我的理解,由于继承用于减少重复,为什么我们应该在子类中定义相同的方法?