Here's code + output that shows conversion of Integer[]
to List<Integer>
:
Integer[] objects = new Integer[]{11, 22, 33};
List<Integer> objectList = Arrays.asList(objects);
System.out.println("object list : " + objectList.toString());
object list : [11, 22, 33]
Here's slightly different code + output that follows the same path, but for int[]
:
int[] primitives = new int[]{11, 22, 33};
List<int[]> primitiveList = Arrays.asList(primitives);
System.out.println("primitive list : " + primitiveList.toString());
System.out.println("first entry : " + Arrays.toString(primitiveList.get(0)));
primitive list : [[I@1218025c, [I@1218025c]
first entry : [11, 22, 33]
I encountered this while working on a practice problem. Without thinking about it too much, I expected to be able to create a List from an array. I only noticed it because IntelliJ flagged Arrays.asList(numbers)
with "call to asList() with only one argument" for the int[]
case. However, since Arrays.asList()
supports varargs, I might have called it with two (or more) different int
arrays and would have seen no warning at all (for example: Arrays.asList(numbers1, numbers2)
).
Arrays.asList()
converts an array to a List
of objects, which works as expected when converting Integer[]
to List<Integer>
. It makes sense that primitive types like int
won't work because creating a List
of primitives isn't allowed, so instead of returning List<int>
it returns List<int[]>
. From JLS 4.3.1. Objects: "An object is a class instance or an array" – clearly though, in the case of Arrays.asList()
, there's a subtlety about whether it's an array of objects or an array of primitives.
Why does it behave this way? Why can't autoboxing work, from int[]
to Integer[]
? Why does the Javadoc for Arrays.asList() make no mention of this behavior with primitive arrays?
Regarding Jon Skeet's answer on this question, specifically: "There's no such thing as a List<int>
in Java - generics don't support primitives. Autoboxing only happens for a single element, not for arrays of primitives." – the answer does not address why generics don't support primitives, nor why autoboxing only happens for a single element, which is the intent of this question.