[英]Boxing with Arrays.asList()
In the following examples: 在以下示例中:
class ZiggyTest2{
public static void main(String[] args){
int[] a = { 1, 2, 3, 4,7};
List<Integer> li2 = new ArrayList<Integer>();
li2 = Arrays.asList(a);
}
}
The compiler complains that that int[] and java.lang.Integer are not compatible. 编译器抱怨int []和java.lang.Integer不兼容。 ie
即
found : java.util.List<int[]>
required: java.util.List<java.lang.Integer>
li2 = Arrays.asList(a);
^
It works fine if i change the List definition to remove the generic types. 如果我更改List定义以删除泛型类型,它工作正常。
List li2 = new ArrayList();
List<Integer>
object from an array of ints using Arrays.asList()? List<Integer>
对象? Thanks 谢谢
Java does not support the auto-boxing of an entire array of primitives into their corresponding wrapper classes. Java不支持将整个基元数组自动装入其对应的包装类中。 The solution is to make your array of type
Integer[]
. 解决方案是使您的数组类型为
Integer[]
。 In that case every int gets boxed into an Integer
individually. 在这种情况下,每个int都会单独装入一个
Integer
。
int[] a = { 1, 2, 3, 4, 7 };
List<Integer> li2 = new ArrayList<Integer>();
for (int i : a) {
li2.add(i); // auto-boxing happens here
}
Removing the generics make it compile, but not work. 删除泛型会使其编译,但不起作用。 Your List will contain one element, which is the
int[]
. 您的列表将包含一个元素,即
int[]
。 You will have to loop over the array yourself, and insert each element in the List
manually 您必须自己遍历数组,并手动插入
List
每个元素
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.