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 int [] and java.lang.Integer are incompatible. those.

 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 generic types.

 List li2 = new ArrayList(); 
  • Should the compiler automatically put int in Integer?
  • How can I create a List<Integer> object from an ints array using Arrays.asList ()?

thanks

+7
source share
2 answers

Java does not support automatic boxing of the entire array of primitives into the corresponding wrapper classes. The solution is to create an array of type Integer[] . In this case, each int is inserted into the 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 } 
+6
source

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

+5
source

All Articles