如何在 Java 中从数组 (int[]) 创建 ArrayList (ArrayList<Integer>) [英] How to create ArrayList (ArrayList<Integer>) from array (int[]) in Java
问题描述
我看到了这个问题:从数组创建 ArrayList
但是,当我使用以下代码尝试该解决方案时,它并不能在所有情况下都有效:
However when I try that solution with following code, it doesn't quite work in all the cases:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
public class ToArrayList {
public static void main(String[] args) {
// this works
String[] elements = new String[] { "Ryan", "Julie", "Bob" };
List<String> list = new ArrayList<String>(Arrays.asList(elements));
System.out.println(list);
// this works
List<Integer> intList = null;
intList = Arrays.asList(3, 5);
System.out.println(intList);
int[] intArray = new int[] { 0, 1 };
// this doesn't work!
intList = new ArrayList<Integer>(Arrays.asList(intArray));
System.out.println(intList);
}
}
我在这里做错了什么?代码不应该intList = new ArrayList
编译就好了吗?
What am I doing wrong here? Shouldn't the code intList = new ArrayList<Integer>(Arrays.asList(intArray));
compile just fine?
推荐答案
问题在
intList = new ArrayList<Integer>(Arrays.asList(intArray));
是 int[]
被视为单个 Object
实例,因为原始数组从 Object
扩展.如果您使用 Integer[]
而不是 int[]
这将起作用,因为现在您正在发送一个 Object
数组.
is that int[]
is considered as a single Object
instance since a primitive array extends from Object
. This would work if you have Integer[]
instead of int[]
since now you're sending an array of Object
.
Integer[] intArray = new Integer[] { 0, 1 };
//now you're sending a Object array
intList = new ArrayList<Integer>(Arrays.asList(intArray));
根据您的评论:如果您仍想使用 int[]
(或其他原始类型数组)作为主数据,则需要使用包装类创建一个额外的数组.对于这个例子:
From your comment: if you want to still use an int[]
(or another primitive type array) as main data, then you need to create an additional array with the wrapper class. For this example:
int[] intArray = new int[] { 0, 1 };
Integer[] integerArray = new Integer[intArray.length];
int i = 0;
for(int intValue : intArray) {
integerArray[i++] = intValue;
}
intList = new ArrayList<Integer>(Arrays.asList(integerArray));
但是由于您已经在使用 for
循环,我不介意使用临时包装类数组,只需将您的项目直接添加到列表中即可:
But since you're already using a for
loop, I wouldn't mind using a temp wrapper class array, just add your items directly into the list:
int[] intArray = new int[] { 0, 1 };
intList = new ArrayList<Integer>();
for(int intValue : intArray) {
intList.add(intValue);
}
这篇关于如何在 Java 中从数组 (int[]) 创建 ArrayList (ArrayList<Integer>)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!