java – 继承Compable与泛型

试图设计一个超类,确保所有子类本身都是可比较的.

/**
 * A base class implementing Comparable with itself by delegation.
 * @param <T> - The type being wrapped.
 */
static class Distinct<T extends Comparable<T>> implements Comparable<Distinct<T>> {
    final T it;
    public Distinct(T it) {
        this.it = it;
    }
    @Override
    public int compareTo(Distinct<T> o) {
        return it.compareTo(o.it);
    }
}
/**
 * A set of distinct items.
 *
 * @param <T>
 */
static class ThingHolder<T extends Comparable<T>> {
    final Set<T> things;
    public ThingHolder() {
        this.things = new TreeSet<>();
    }
}
/**
 * A sample real thing.
 */
static class Thing extends Distinct<String> {
    public Thing(String it) {
        super(it);
    }
}
// This doesn't work - Why?
final ThingHolder<Thing> yz = new ThingHolder<>();

我得到的错误是:

com/oldcurmudgeon/test/Test.java:[70,22] error: type argument Thing is not within bounds of type-variable T
  where T is a type-variable:
    T extends Comparable<T> declared in class ThingHolder

为什么这不起作用?可以吗?

解决方法:

>如果将类型参数X传递给ThingHolder,则它必须是Comparable< X>的子类型. (通过ThingHolder的类声明).
>因此,如果你将Thing类型传递给ThingHolder,它必须是Comparable< Thing>的子类型. (根据之前的陈述,将Thing替换为X.)
> Thing扩展Distinct< String>因此实现了Comparable< Distinct< String>> (通过Thing的类声明).
> Thing与Distinct< String>的类型不同 – 虽然它是一个子类型 – 因此类型匹配失败.

你可以通过调整ThingHolder的类声明来解决这个问题,如下所示:

class ThingHolder<T extends Comparable<? super T>> {
    ...
}
上一篇:java – 可比较不排序对象


下一篇:Java——四个重要接口