简体   繁体   English

怎么会 <T extends Comparable<T> &gt;作为 <T extends Comparable<? super T> &gt;?

[英]How come <T extends Comparable<T>> working as <T extends Comparable<? super T>>?

suppose we have 假设我们有

class Fruit implements Comparable<Fruit>
{
    @Override
    public int compareTo(Fruit o) { return 0; }
}

class Apple extends Fruit{}

class Main
{

    public static void main (String args[])
    {
        function(new Apple()); // this shouldn't work because Apple is implementing Comparable<Fruit>, not Comparable<Apple>
    }

    public static<T extends Comparable<T>> void function(T t){}
} 

Code is working without any issue. 代码可以正常工作。

My question is why <T extends Comparable<T>> working like <T extends Comparable<? super T>> 我的问题是为什么<T extends Comparable<T>><T extends Comparable<? super T>>一样工作<T extends Comparable<? super T>> <T extends Comparable<? super T>> . <T extends Comparable<? super T>> whats the difference ? 有什么不同 ?

Thanks. 谢谢。

[Edited] - A passage from book Image [编辑]-图书图片的一段

In this case it is beacuse class Fruit is a superclass of itself 在这种情况下,是因为类Fruit是自身的超类

The difference is here 区别在这里

<T extends Comparable<T>> accepts Comparable with arguement of type T <T extends Comparable<? super T>> <T extends Comparable<T>>接受Comparable与type T争论<T extends Comparable<? super T>> <T extends Comparable<? super T>> accepts Comparable with arguements of type T and its super classes . <T extends Comparable<? super T>>接受<T extends Comparable<? super T>> type T and its super classes其父type T and its super classes争论。 Here Since in java every class is a superclass of itself, Fruit is also a superclass of Fruit .Thats why you see like they are working the same way But if you used class Apple as T you will see the difference. 由于在Java中每个类都是其自身的超类,因此Fruit is also a superclass of Fruit这就是为什么您看到它们以相同的方式工作的原因,但是如果您将Apple类用作T您会发现其中的区别。

You compile with Java 8 I think. 我认为您可以使用Java 8进行编译。 Because, before Java 8, you should not pass the compilation and have this error : 因为在Java 8之前,您不应该通过编译并出现以下错误:

Bound mismatch: The generic method function(T) of type Main is not applicable for the arguments (Apple). 边界不匹配:Main类型的通用方法函数(T)不适用于自变量(Apple)。 The inferred type Apple is not a valid substitute for the bounded parameter > 推断的类型Apple不是边界参数的有效替代品>

I think what you read in your book refers to generic use before Java 8. 我认为您在书中所读的内容是指Java 8之前的通用用法。
But i didn't know that Java 8 had less constraint on this kind of case. 但是我不知道Java 8对这种情况的约束较少。
Is it a side-effect of the large use of inference in Java 8 that Java 8 calls the "improved inference" ? Java 8称为“改进的推理”是否是Java 8中大量使用推理的副作用?

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

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