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?
基础教程推荐
- 如何对 Java Hashmap 中的值求和 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
