为什么尝试更新对象列表的值时会引发异常?

huangapple go评论78阅读模式
英文:

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&lt;Integer&gt;, but that's wrong.
Arrays.asList(int[]) creates a List&lt;int[]&gt;, 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&lt;Integer&gt; 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&lt;Integer&gt; been used as the data type of list)

huangapple
  • 本文由 发表于 2020年9月24日 15:16:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64041302.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定