Java 接口扩展了 Comparable
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2231804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java interface extends Comparable
提问by oceola
I want to have an interface A
parameterised by T
A<T>
, and also want every class that implements it to also implement Comparable
(with T
and its subtypes). It would seem natural to write interface A<T> extends Comparable<? extends T>
, but that doesn't work. How should I do it then?
我希望有一个A
由 参数化的接口T
A<T>
,并且还希望实现它的每个类也实现Comparable
(使用T
及其子类型)。写起来似乎很自然interface A<T> extends Comparable<? extends T>
,但这行不通。那我该怎么做呢?
回答by finnw
When Comparable<? extends T>
appears it means you have an instance of Comparable
that can be compared to one (unknown) subtype of T
, not that it can be compared to anysubtype of T.
当Comparable<? extends T>
出现时,表示您有一个Comparable
可以与 的一个(未知)子类型进行比较的实例T
,而不是可以与T 的任何子类型进行比较。
But you don't need that, because a Comparable<T>
can compare itself to any subtype of T
anyway, e.g. a Comparable<Number>
can compare itself to a Comparable<Double>
.
但是你不需要那个,因为 aComparable<T>
可以将自己与任何子类型进行比较T
,例如 aComparable<Number>
可以将自己与 a 进行比较Comparable<Double>
。
So try:
所以尝试:
interface A<T> extends Comparable<T> {
// ...
}
or
或者
interface A<T extends Comparable<T>> extends Comparable<A<T>> {
// ...
}
depending on whether you need to be able to compare instances of T
in order to implement your compareTo
method.
取决于您是否需要能够比较实例T
以实现您的compareTo
方法。
回答by Nils Schmidt
If you use comparable you do not need to specify the possibility for subtypes in the compare function, it is by nature possible to pass in any subtype of an object X into a method that declared a parameter of class X. See the code below for more information.
如果使用可比较,则不需要在比较函数中指定子类型的可能性,本质上可以将对象 X 的任何子类型传递到声明类 X 参数的方法中。有关更多信息,请参阅下面的代码信息。
public interface Test<T> extends Comparable<T> {
}
class TestImpl implements Test<Number> {
@Override
public int compareTo(final Number other) {
return other.intValue() - 128;
}
}
class TestMain {
public static void main(final String[] args) {
TestImpl testImpl = new TestImpl();
testImpl.compareTo(Integer.MIN_VALUE);
}
}