我有一个如下声明的列表:
List<? extends Number> foo3 = new ArrayList<Integer>();
我尝试将3加到foo3中。但是,我得到如下的错误消息:
The method add(capture#1-of ? extends Number) in the type List<capture#1-of ?
extends Number> is not applicable for the arguments (ExtendsNumber)
发布于 2010-05-06 05:39:42
你不能(没有不安全的类型转换)。您只能从它们中读取。
问题是你不知道这个列表到底是什么。它可以是Number的任何子类的列表,所以当您尝试将一个元素放入其中时,您不知道该元素实际上是否适合该列表。
例如,列表可能是Byte
的列表,因此将Float
放入其中将是错误的。
发布于 2010-05-06 05:48:32
你可以这样做:
List<Number> foo3 = new ArrayList<Number>();
foo3.add(3);
发布于 2020-07-25 03:32:32
您可以通过创建一个具有不同类型的列表引用来对其进行虚构。
(这些是sepp2k提到的“不安全类型转换”。)
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);
因为untypedList
、superclassedList
和trulyclassedList
只是对list
的引用,所以仍然需要向原始ArrayList添加元素。
在上面的示例中,您实际上不需要使用(List<?>)
,但是您可能需要在代码中使用它,这取决于提供给您的list
的类型。
注意,使用?
会给你编译器警告,直到你把它放在你的函数上面:
@SuppressWarnings("unchecked")
https://stackoverflow.com/questions/2776975
复制相似问题