简体   繁体   English

Java接口扩展了Comparable

[英]Java interface extends Comparable

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). 我希望有一个由T A<T>参数化的接口A ,并且还希望实现它的每个类也实现Comparable (使用T及其子类型)。 It would seem natural to write interface A<T> extends Comparable<? extends T> 编写interface A<T> extends Comparable<? extends T>似乎很自然interface A<T> extends Comparable<? extends T> interface A<T> extends Comparable<? extends T> , but that doesn't work. interface A<T> extends Comparable<? extends T> ,但这不起作用。 How should I do it then? 那我该怎么办?

When Comparable<? extends T> Comparable<? extends T> 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 any subtype 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, eg a Comparable<Number> can compare itself to a Comparable<Double> . 但是你不需要它,因为Comparable<T>可以将自己与T任何子类型进行比较,例如, Comparable<Number>可以将自身与Comparable<Double>进行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方法。

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM