英文:
Converting primitive array of int into ArrayList in Java: "java.lang.ClassCastException: [I cannot be cast to java.lang.Integer"
问题
我想知道如何将一个整数的原始数组转换成一个整数列表?
对于以下代码没有编译错误:
int[] nums = {0, 1};
List<Integer> list = new ArrayList(Arrays.asList(nums));
list.get(0);
但是这段代码:
int[] nums = {0, 1};
List<Integer> list = new ArrayList(Arrays.asList(nums));
int a = list.get(0);
会产生失败:
java.lang.ClassCastException: 无法将类 [I 强制转换为类 java.lang.Integer ([I 和 java.lang.Integer 在加载器 'bootstrap' 的 java.base 模块中)
英文:
I'm wondering how I can convert a primitive array of integers to a list of Integer?
There's no compile error for:
int[] nums = {0, 1};
List<Integer> list = new ArrayList(Arrays.asList(nums));
list.get(0);
But this one:
int[] nums = {0, 1};
List<Integer> list = new ArrayList(Arrays.asList(nums));
int a = list.get(0);
fails with:
java.lang.ClassCastException: class [I cannot be cast to class java.lang.Integer ([I and java.lang.Integer are in module java.base of loader 'bootstrap')
答案1
得分: 2
解决方案1:
在Java 8中:
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toCollection(ArrayList::new));
注意: 你可能需要:
import java.util.stream.Collectors;
解决方案2:
使用for循环:
List<Integer> list = new ArrayList();
for(int n : nums) {
list.add(n);
}
解决方案3:
将原始数组声明为Integer[]
,而不是int[]
:
Integer[] nums = {0, 1};
英文:
Solution 1:
In Java 8:
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toCollection(ArrayList::new));
Note: You might need to:
import java.util.stream.Collectors;
Solution 2:
Use for loop:
List<Integer> list = new ArrayList();
for(int n : nums) {
list.add(n);
}
Solution 3:
Declare the original array as Ingeger[]
instead of int[]
:
Integer[] nums = {0, 1};
答案2
得分: 0
代码Arrays.asList(nums)
不会被翻译为包含两个值的ArrayList
,即1和2。它只有一个值,即int[] { 1, 2 }
。为了创建正确的ArrayList
,您应该使用:
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
英文:
The code Arrays.asList(nums)
won't translate to an ArrayList
with 2 values, viz. 1 and 2. It just has one value, int[] { 1, 2 }
. In order to create the right ArrayList
, you should use
List<Integer> list = Arrays.stream(nums).boxed().collect(Collectors.toList());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论