[英]Inheriting Comparable with generics
试图设计一个超类,确保所有子类本身都是Comparable
。
/**
* 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>
类型Distinct<String>
- 尽管它是一个子类型 - 因此类型匹配失败。 你可以通过调整ThingHolder
的类声明来解决这个ThingHolder
,如下所示:
class ThingHolder<T extends Comparable<? super T>> {
...
}
一些研究和抨击提出了这个建议 。
通常,如果您的API只使用类型参数T作为参数,则其使用应该利用较低的有界通配符(?super T)。
一些修补(添加? super T
)略微放松限制叶:
/**
* A set of distinct items.
*
* Don't like the <?> in there but a <T> is not accepted.
*
* @param <T>
*/
static class ThingHolder<T extends Comparable<? super T>> {
final Set<T> things = new TreeSet<>();
}
final ThingHolder<Thing> holder = new ThingHolder<>();
这对编译器来说是可以接受的。
一般我不喜欢用?
为了填补空白,因为它通常允许过多,但在这种情况下,我会留下它。
只需将ThingHolder
类签名更改为:
static class ThingHolder<T extends Comparable> {
...
}
即从Comparable
删除<T>
,没有必要。
class ThingHolder<T extends Comparable<T>>
声明事物 T
必须与自身相当,但class Thing extends Distinct<String>
不是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.