小编fra*_*liu的帖子

使用泛型类实现Comparable

我想定义一个实现通用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 generics interface comparable raw-types

15
推荐指数
2
解决办法
5万
查看次数

java集合接口中的继承

Java集合接口中存在一些继承关系.例如,Collection<T>接口将扩展Iterable<T>.我检查了JDK中的源代码,基类中定义的一些方法在子类中多次重复.例如: Interable<T>接口中定义的方法 Iterator<E> iterator();,但在接口Collection<E>List<T>,也含有相同的方法.根据我的理解,由于继承用于减少重复,为什么我们应该在子类中定义相同的方法?

java collections interface

7
推荐指数
2
解决办法
1836
查看次数

标签 统计

interface ×2

java ×2

collections ×1

comparable ×1

generics ×1

raw-types ×1