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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 05:01:37  来源:igfitidea点击:

Java interface extends Comparable

javagenericsinheritanceinterface

提问by oceola

I want to have an interface Aparameterised by TA<T>, and also want every class that implements it to also implement Comparable(with Tand 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由 参数化的接口TA<T>,并且还希望实现它的每个类也实现Comparable(使用T及其子类型)。写起来似乎很自然interface A<T> extends Comparable<? extends T>,但这行不通。那我该怎么做呢?

回答by finnw

When Comparable<? extends T>appears it means you have an instance of Comparablethat 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 Tanyway, 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 Tin order to implement your compareTomethod.

取决于您是否需要能够比较实例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);
    }
}