英文:
Why list of objects throws an exception when trying to update it's value?
问题
为什么以下代码在第3行抛出 ArrayStoreException 异常:
int[] ar = {2, 4};
List list = Arrays.asList(ar);
list.set(0, 3);
在这里应该执行从 Integer 到 int 的拆箱操作,但实际未执行。
英文:
Why the following code throws ArrayStoreException on line 3:
int[] ar = {2, 4};
List list = Arrays.asList(ar);
list.set(0, 3);
Unboxing should be performed here from Integer to int but it doesn't.
答案1
得分: 1
你假设 Arrays.asList(ar)
创建了一个 List<Integer>
,但这是错误的。
Arrays.asList(int[])
创建的是一个 List<int[]>
,并且在这个数组中设置一个 int
类型的元素会导致 ArrayStoreException
(将一个 int
保存在 int[]
数组中)。
如果你想要得到一个带有相同代码的 List<Integer>
,请将 ar
声明为 Integer[]
。这可能是另一个教训,要避免使用原始类型(因为如果 list
的数据类型使用了 List<Integer>
,编译器就会阻止这个运行时异常)
英文:
You're assuming that Arrays.asList(ar)
creates a List<Integer>
, but that's wrong.
Arrays.asList(int[])
creates a List<int[]>
, and setting an element of type int
in that array explains the ArrayStoreException
(saving an int
in an int[]
array).
If you want a List<Integer>
with the same code, declare ar
as Integer[]
. This is probably another lesson to avoid using raw types (because the compiler would have prevented this runtime exception, had List<Integer>
been used as the data type of list
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论