为什么是SomeClass<?超T>不等同于SomeClass< T>在Java泛型类型? [英] Why is SomeClass<? super T> not equivalent to SomeClass<T> in Java generic types?
问题描述
public static< T> void sort(List< T> list,Comparator< ;? super T> c)
?super
这里需要吗?如果 ClassB
扩展 ClassA
,那么我们不能保证比较器< ClassA> ; ?可以比较两个
ClassB
对象,不需要?super
部分?
换句话说,给出以下代码:
List< ; ClassB的> list =。 。 。 ;
比较器< ClassA> comp =。 。 。 ;
Collections.sort(list,comp);
为什么编译器不够聪明,即使没有指定<$ c对于Collections.sort()的声明,$ c>?super >
Josh Bloch今年在Google I / O上进行了一次演讲,名为有效的Java Reloaded ,您可能会感兴趣。它讲述了一个名为Pecs的助记符(生产者 extends
,consumer super
),这就解释了为什么使用?扩展T
和?超级T
在您的输入参数(只;从来没有返回类型),以及何时使用。
I noticed the specificaition for Collections.sort:
public static <T> void sort(List<T> list, Comparator<? super T> c)
Why is the "? super
" necessary here? If ClassB
extends ClassA
, then wouldn't we have a guarantee that a Comparator<ClassA>
would be able to compare two ClassB
objects anyway, without the "? super
" part?
In other words, given this code:
List<ClassB> list = . . . ;
Comparator<ClassA> comp = . . . ;
Collections.sort(list, comp);
why isn't the compiler smart enough to know that this is OK even without specifying "? super
" for the declaration of Collections.sort()?
Josh Bloch had a talk at Google I/O this year, called Effective Java Reloaded, which you may find interesting. It talks about a mnemonic called "Pecs" (producer extends
, consumer super
), which explains why you use ? extends T
and ? super T
in your input parameters (only; never for return types), and when to use which.
这篇关于为什么是SomeClass<?超T>不等同于SomeClass< T>在Java泛型类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!