<E extends Number> 和有什么区别?和<号码>? [英] What is the difference between <E extends Number> and <Number>?
问题描述
这个方法声明有什么区别:
What is the difference between this method declaration:
public static <E extends Number> List<E> process(List<E> nums){
和
public static List<Number> process(List<Number> nums){
你会在哪里使用前者?
推荐答案
第一个允许 process
一个 List
,一个 List
等.第二个没有.
The first allows process
of a List<Integer>
, a List<Double>
, etc. The second doesn't.
Java 中的泛型是不变的.它们不像数组那样是协变的.
Generics in Java are invariant. They're not covariant like arrays.
也就是说,在 Java 中,Double[]
是 Number[]
的子类型,但是 List
不是一个List
的子类型.但是,List
是 List
.
That is, in Java, 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
和 super
类型对于子类型灵活性通常是必要的.
There are good reasons for generics being invariant, but that's also why the extends
and super
type are often necessary for subtyping flexibility.
- Java 教程/泛型/子类型
- 解释为什么泛型不变性是一件好事
- 解释
super
和extends
的一些用途,用于有界通配符
- Explains some uses of
super
andextends
for bounded wildcards
- 这里讨论了Producer
extends
Consumersuper
"原则 - Effective Java 2nd Edition,第 28 条:使用有界通配符提高 API 灵活性
- This discusses the "Producer
extends
Consumersuper
" principle - Effective Java 2nd Edition, Item 28: Use bounded wildcards to increase API flexibility
这篇关于<E extends Number> 和有什么区别?和<号码>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!