Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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();
  • 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

like image 540
ziggy Avatar asked Dec 05 '11 14:12

ziggy


2 Answers

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
}
like image 115
Matt Avatar answered Sep 22 '22 03:09

Matt


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

like image 33
Robin Avatar answered Sep 22 '22 03:09

Robin