Converting primitive array of int into ArrayList in Java: "java.lang.ClassCastException: [I cannot be cast to java.lang.Integer"

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

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&lt;Integer&gt; list = new ArrayList(Arrays.asList(nums));
	list.get(0);

But this one:

	int[] nums = {0, 1};
	List&lt;Integer&gt; 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 &#39;bootstrap&#39;) 

答案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&lt;Integer&gt; 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&lt;Integer&gt; 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&lt;Integer&gt; list = Arrays.stream(nums).boxed().collect(Collectors.toList());

huangapple
  • 本文由 发表于 2020年10月21日 08:28:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/64455014.html
匿名

发表评论

匿名网友

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

确定