无法将对象添加到List<?>实例化为ArrayList< Object> [英] Cannot add an object to List<?> instantiated as ArrayList<Object>
问题描述
我问这个问题是因为关于Stack的一个答案的讨论。声明如下:
给定以下代码:
列表与LT;?> list = new ArrayList< Integer>();
为什么我们不能这样做:
Integer e = 2;
list.add(e);
这会引发编译器错误,尽管我们将列表实例化为 ArrayList< Integer>
。
为什么会这样? 解析方案因为 List<>
可以是任何种类的List( List< String>
例如)。然而,如果你知道实际的类,那么你可以在运行时进行类转换:
这样的代码应该避免,因为如果在运行时遇到意外的类型,它可能会生成ClassCastException。更糟的是(正如 luk2302 所述),我们的ClassCastException可能只发生在完全不同的代码区域 - 即当我们从列表中检索某些东西的时候。
更好的方法
如果您知道该列表将是特定类型或该类型的超类,那么您可以使用有界通配符来定义变量:
列表与LT ;?超整型>列表;
整数e = 2;
list = new ArrayList< Integer>();
list.add(e);
list = new ArrayList< Number>();
list.add(e);
list = new ArrayList< Object>();
list.add(e);
这种方法,如微米。普罗克霍夫,让我们可以避免不必要的演员阵容。
I ask this question because of a discussion about one answer here on Stack. The statement is the following:
Given the following code:
List<?> list =new ArrayList<Integer>();
Why can't we do:
Integer e = 2;
list.add(e);
This throws a compiler error, despite the fact that we instantiated the list as an ArrayList<Integer>
.
Why is that ?
Because a List<?>
could be any sort of List (List<String>
for example). And the compiler should not permit adding the wrong type to a list.
However, if you know the actual class then you can do a class cast at runtime:
((List<Integer>)list).add(e);
Code like this should be avoided since it can generate a ClassCastException if an unexpected type is encountered at runtime. To make matters worse (as noted by luk2302), our ClassCastException might only occur in an entirely different area of the code-- namely, when we are retrieving something from the list.
A better approach
If you know that the list will be of a specific type or a superclass of that type, then you could define the variable using a bounded wildcard:
List<? super Integer> list;
Integer e = 2;
list = new ArrayList<Integer>();
list.add(e);
list = new ArrayList<Number>();
list.add(e);
list = new ArrayList<Object>();
list.add(e);
This approach, as noted by M. Prokhorov, allows us to avoid the need for an inadvisable cast.
这篇关于无法将对象添加到List<?>实例化为ArrayList< Object>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!