Why java does not autobox int[] to Integer[]

后端 未结 5 2219
-上瘾入骨i
-上瘾入骨i 2020-12-16 02:45

When I do the following,

  • arrayList1 - contains one element and it is an int[].
  • arrayList2 - not compiling (Err
5条回答
  •  太阳男子
    2020-12-16 03:06

    The difference is int[] is itself an Object, whereas Integer[] is an array of references to Integer object.

    Arrays.asList(T...) method takes variable arguments of some type T with no upper bounds. The erasure of that method is Arrays.asList(Object...). That means it will take variable number of arguments of any type that extends from Object.

    Since int is not an Object, but a primitive type, so it can't be passed as individual element of T[], whereas int[] is an Object itself, it will go as first element of the T[] array (T... internally is a T[] only). However, Integer[] will be passed as T[], with each reference in Integer[] passed as different argument to T[].

    And even if you would argue that compiler should have done the conversion from each element of int[] array to Integer, well that would be too much work for the compiler. First it would need to take each array element, and box it to Integer, then it would need to internally create an Integer[] from those elements. That is really too much. It already has a direct conversion from int[] to Object, which it follows. Although I have always wished Java allowed implicit conversion from int[] to Integer[], that would have made life simpler while working with generics, but again, that's how the language is designed.

    Take a simple example:

    Object[] array = new Integer[10];  // this is valid conversion
    Object[] array2 = new int[10];     // this is not
    Object obj = new int[10];          // this is again a valid conversion
    

    So, in your code Arrays.asList(intArray) returns a ArrayList and not ArrayList. You can't pass it to the ArrayList() constructor.


    Related:

    • int[] and Integer[]: What is the difference?

提交回复
热议问题