且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 java 不会将 int[] 自动装箱为 Integer[]

更新时间:2023-09-18 10:23:34

区别在于 int[] 本身是一个 Object,而 Integer[] 是对 Integer 对象的引用数组.

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

Arrays.asList(T...) 方法采用某种类型 T 的变量参数,没有上限.该方法的擦除是Arrays.asList(Object...).这意味着它将采用从 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.

由于int不是Object,而是一个原始类型,所以不能作为T[]的单个元素传递,而 int[] 本身是一个 Object,它将作为 T[] 数组的第一个元素(T... 内部只是一个 T[]).但是,Integer[] 将作为 T[] 传递,Integer[] 中的每个引用作为不同的参数传递给 T[].

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[].

即使您认为编译器应该完成从 int[] 数组的每个元素到 Integer 的转换,那么这对于编译器.首先它需要获取每个数组元素,并将其装箱为 Integer,然后它需要从这些元素内部创建一个 Integer[].这实在是太过分了.它已经有一个从 int[]Object 的直接转换,它遵循它.虽然我一直希望 Java 允许从 int[]Integer[] 的隐式转换,这会使使用泛型时的生活更简单,但同样,这就是语言的方式设计.

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.

举个简单的例子:

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

所以,在你的代码中 Arrays.asList(intArray) 返回一个 ArrayList 而不是 ArrayList.你不能把它传递给 ArrayList() 构造函数.

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

相关: