4

The following is throws compile error:

int[] arrs = {1,2,4,3,5,6};
List<Integer> arry = Arrays.asList(arrs);

but this works:

for (Integer i : arrs){
   //do something
}

Auto-boxing works in many contexts, I just gave one example of for-loop above. but it fails in the List-view that I make in Arrays.asList().

Why does this fail and why is such as a design implementation chosen?

Pshemo
  • 122,468
  • 25
  • 185
  • 269
brain storm
  • 30,124
  • 69
  • 225
  • 393

3 Answers3

6

To make things work you need to use Integer[] instead of int[].

Argument of asList is of type T... and generic types T can't represent primitive types int, so it will represent most specific Object class, which in this case is array type int[].
That is why Arrays.asList(arrs); will try to return List<int[]> instead of List<int> or even List<Integer>.

Some people expect automatic conversion from int[] to Integer[], but lets nor forget that autoboxing works only for primitive types, but arrays are not primitive types.

Pshemo
  • 122,468
  • 25
  • 185
  • 269
2

The Arrays.asList takes generic T[] as argument. This T is always an object, not a primitive. When you give an int[] as parameter (not an array of objects but primitives) it'll think the argument is actually the first element of the vararg. So the resulting list will have the fingerprint List<int[]> instead.

If you want to learn more about generics in Arrays, please read this page: http://docs.oracle.com/javase/tutorial/extra/generics/fineprint.html (part: Arrays)

Roy van Rijn
  • 840
  • 7
  • 17
1

Arrays.asList() takes a arbitrary number of arguments of given type T (#asList(T.. t)). Calling Arrays.asList(arrs) what you really do is passing single element of type int[] hence the problem. It should be either:

int[] arrs = {1,2,4,3,5,6};
List<int[]> arry = Arrays.asList(arrs);

or

List<Integer> arry = Arrays.asList(1,2,3,4,5,6);

somenickname
  • 539
  • 7
  • 19
slawek
  • 11
  • 1