Question

I would like to know why autoboxing does not occur in the following:

int [] array = new int[]{1,3,6,2,-1,6};// if it had been Integer instead of int, would have worked.
List<Integer> liston = Arrays.asList(array);

Is there any particular reason why it does not autobox automatically?

Thanks in advance.

Was it helpful?

Solution

you can read on Autoboxing here:

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

and as you can read at the end, the types tat are auto boxed are: boolean, byte, char, float, int, long and short. array are not autoboxed

it might seems very logical for you that the compiler will do that, but that kind of behavior is very complicated and required a very sophisticated compiler.

OTHER TIPS

Why would autoboxing be needed here?

  • argument of Array.asList is varargs T... which can be interpreted as T[]
  • generics require Object type,

If you pass Integer[] then T in T[] will be understood as Integer so Array.asList will return List<Integer>.
But if you pass array (and all arrays are also Object type) then T can (and will) be int[] making result of Array.asList List<int[]>.

Demo.

int[] array = new int[]{1,3,6,2,-1,6};
//                        |
//                        +-----------------------+
List<int[]> liston = Arrays.asList(array);//      |
System.out.println(liston.get(0)[1]);//will print 3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top