为什么不能在上限泛型列表中添加元素? [英] Why can't add element in a upper bound generics List?

查看:315
本文介绍了为什么不能在上限泛型列表中添加元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有上限泛型的列表。

I have a list with upper bound generics.

 List<? extends Number> l = new ArrayList<>();
 l.add(new Integer(3));  //ERROR
 l.add(new Double(3.3)); // ERROR

我不明白这个问题,因为Integer和Double扩展了数字。

I don't understand the problem, because Integer and Double extend Number.

推荐答案

列表<? extends Number> 并不意味着一个列表可以容纳 Number 的子类的所有对象,它意味着一个参数化为一个具体类的列表扩展数字。它不是你定义的列表本身的内容,它是分配给变量的实际列表对象的参数化类型可以是什么(男孩,这比理解它更难解释:))

List<? extends Number> does not mean "a list that can hold all objects of subclasses of Number", it means "a list parameterized to one concrete class that extends Number". It's not the contents of the list itself you are defining, it's what the parameterized type of the actual list-object assigned to the variable can be (boy, this is harder to explain than it is to understand :) )

所以,你可以这样做:

List<? extends Number> l = new ArrayList<Integer>();
List<? extends Number> l = new ArrayList<Double>();

如果你想要一个能够容纳类号或其子类的任何对象的列表,那就做这个:

If you want a list that is able to hold any object of class Number or its subclasses, just do this:

List<Number> l = new ArrayList<>();

l.add(new Integer(33));
l.add(new Double(33.3d));

(插入值的装箱是不必要的,但为了清晰起见..)

(The boxing of the values inserted is unnecessary, but there for clarity..)

这篇关于为什么不能在上限泛型列表中添加元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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