首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何添加到List<?扩展Number>数据结构?

如何添加到List<?扩展Number>数据结构?
EN

Stack Overflow用户
提问于 2010-05-06 05:38:00
回答 4查看 79.2K关注 0票数 173

我有一个如下声明的列表:

代码语言:javascript
复制
 List<? extends Number> foo3 = new ArrayList<Integer>();

我尝试将3加到foo3中。但是,我得到如下的错误消息:

代码语言:javascript
复制
The method add(capture#1-of ? extends Number) in the type List<capture#1-of ?
extends Number> is not applicable for the arguments (ExtendsNumber)
EN

回答 4

Stack Overflow用户

发布于 2010-05-06 05:39:42

你不能(没有不安全的类型转换)。您只能从它们中读取。

问题是你不知道这个列表到底是什么。它可以是Number的任何子类的列表,所以当您尝试将一个元素放入其中时,您不知道该元素实际上是否适合该列表。

例如,列表可能是Byte的列表,因此将Float放入其中将是错误的。

票数 19
EN

Stack Overflow用户

发布于 2010-05-06 05:48:32

你可以这样做:

代码语言:javascript
复制
  List<Number> foo3 = new ArrayList<Number>();      
  foo3.add(3);
票数 1
EN

Stack Overflow用户

发布于 2020-07-25 03:32:32

您可以通过创建一个具有不同类型的列表引用来对其进行虚构。

(这些是sepp2k提到的“不安全类型转换”。)

代码语言:javascript
复制
List<? extends Number> list = new ArrayList<Integer>();

// This will not compile
//list.add(100);

// WORKS, BUT NOT IDEAL
List untypedList = (List)list;
// It will let you add a number
untypedList.add(200);
// But it will also let you add a String!  BAD!
untypedList.add("foo");

// YOU PROBABLY WANT THIS
// This is safer, because it will (partially) check the type of anything you add
List<Number> superclassedList = (List<Number>)(List<?>)list;
// It will let you add an integer
superclassedList.add(200);
// It won't let you add a String
//superclassedList.add("foo");
// But it will let you add a Float, which isn't really correct
superclassedList.add(3.141);
// ********************
// So you are responsible for ensuring you only add/set Integers when you have
// been given an ArrayList<Integer>
// ********************

// EVEN BETTER
// If you can, if you know the type, then use List<Integer> instead of List<Number>
List<Integer> trulyclassedList = (List<Integer>)(List<?>)list;
// That will prevent you from adding a Float
//trulyclassedList.add(3.141);

System.out.println("list: " + list);

因为untypedListsuperclassedListtrulyclassedList只是对list的引用,所以仍然需要向原始ArrayList添加元素。

在上面的示例中,您实际上不需要使用(List<?>),但是您可能需要在代码中使用它,这取决于提供给您的list的类型。

注意,使用?会给你编译器警告,直到你把它放在你的函数上面:

代码语言:javascript
复制
@SuppressWarnings("unchecked")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2776975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档