使用Arrays.asList() [英] Boxing with Arrays.asList()
本文介绍了使用Arrays.asList()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在以下示例中:
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);
}
}
编译器提示int [ ]和java.lang.Integer不兼容。
The compiler complains that that int[] and java.lang.Integer are not compatible. i.e.
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 li2 = new ArrayList();
- 编译器是否应该自动将ints赋值为Integer?
- 如何使用
Arrays.asList()从一个int数组创建一个List< Integer>
- Shouldn't the compiler have auto-boxed the ints to Integer?
- How can i create a
List<Integer>
object from an array of ints using Arrays.asList()?
感谢
推荐答案
不支持将原始元素的整个数组自动装入到其相应的包装类中。解决方案是使你的数组 Integer []
。在这种情况下,每个int都被单独装入 Integer
。
Java does not support the auto-boxing of an entire array of primitives into their corresponding wrapper classes. The solution is to make your array of type Integer[]
. In that case every int gets boxed into an Integer
individually.
int[] a = { 1, 2, 3, 4, 7 };
List<Integer> li2 = new ArrayList<Integer>();
for (int i : a) {
li2.add(i); // auto-boxing happens here
}
这篇关于使用Arrays.asList()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文