简体   繁体   中英

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. 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 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()?

Thanks

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
}

Removing the generics make it compile, but not work. Your List will contain one element, which is the int[] . You will have to loop over the array yourself, and insert each element in the List manually

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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