简体   繁体   English

拳击与Arrays.asList()

[英]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();
  • 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()? 如何使用Arrays.asList()从int数组创建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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM