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();
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With