<E extends Number> 和有什么区别?和<号码>? [英] What is the difference between <E extends Number> and <Number>?

查看:31
本文介绍了<E extends 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 的子类型.但是,ListList.

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>.

泛型具有不变性是有充分理由的,但这也是为什么 extendssuper 类型对于子类型灵活性通常是必要的.

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 教程/泛型/子类型
    • 解释为什么泛型不变性是一件好事
    • 解释superextends 的一些用途,用于有界通配符
    • Explains some uses of super and extends for bounded wildcards
    • 这里讨论了Producer extends Consumer super"原则
    • Effective Java 2nd Edition,第 28 条:使用有界通配符提高 API 灵活性
    • This discusses the "Producer extends Consumer super" principle
    • Effective Java 2nd Edition, Item 28: Use bounded wildcards to increase API flexibility

    这篇关于&lt;E extends Number&gt; 和有什么区别?和&lt;号码&gt;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆