why does auto-boxing and unboxing of integers does not work with Arrays.asList in Java?(为什么整数的自动装箱和拆箱不适用于 Java 中的 Arrays.asList?)
问题描述
以下是抛出编译错误:
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.
这篇关于为什么整数的自动装箱和拆箱不适用于 Java 中的 Arrays.asList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么整数的自动装箱和拆箱不适用于 Java 中的 Arrays.asList?
基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 多个组件的复杂布局 2022-01-01
