为什么整数的自动装箱和拆箱不适用于 Java 中的 Arrays.asList?

2022-01-20 00:00:00 复制 list arrays java autoboxing

以下是抛出编译错误:

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

但这有效:

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

自动装箱在许多情况下都有效,我只是在上面给出了一个 for-loop 的例子.但它在我在 Arrays.asList() 中制作的 List-view 中失败了.

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?

推荐答案

要使事情正常运行,您需要使用 Integer[] 而不是 int[].

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

asList 的参数是 T... 类型,泛型类型 T 不能表示原始类型 int,因此它将代表最具体的 Object 类,在这种情况下是数组类型 int[].
这就是为什么 Arrays.asList(arrs); 会尝试返回 List<int[]> 而不是 List<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>.

有些人期望从 int[]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.

相关文章