< E extensions Number>之间的区别是什么?和< Number> ;? [英] What is the difference between <E extends Number> and <Number>?
问题描述
这个方法声明有什么区别:
public static< E extends Number>列表与LT E - 代替;进程(列表< E>数量){
和
public static List< Number> process(List< Number> nums){
您会在哪里使用前者?
第一个允许 List
/ code>,a 列表< Double>
等等。第二个不是。
泛型在Java中是不变的。它们不像数组那样是协变的。
即在Java中, Double []
是子类型 Number []
,但是 List< Double>
不是 List< Number>的子类型。
。然而,列表< Double>
是列表< ;?扩展数字>
。
泛型不变的原因很多,但这也是为什么 What is the difference between this method declaration: and Where would you use the former? The first allows Generics in Java are invariant. They're not covariant like arrays. That is, in Java, There are good reasons for generics being invariant, but that's also why the 这篇关于< E extensions Number>之间的区别是什么?和< Number> ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!扩展
和 super
类型通常是子类型灵活性所必需的。 另见
super
和 extends $的一些用法c $ c>限制通配符
extends
消费者 super
p原理
public static <E extends Number> List<E> process(List<E> nums){
public static List<Number> process(List<Number> nums){
process
of a List<Integer>
, a List<Double>
, etc. The second doesn't.Double[]
is a subtype of Number[]
, but a List<Double>
is NOT a subtype of List<Number>
. A List<Double>
, however, is a List<? extends Number>
.extends
and super
type are often necessary for subtyping flexibility.See also
super
and extends
for bounded wildcards
extends
Consumer super
" principle