如何创建的ArrayList(ArrayList的<整数GT;)从阵列中的Java(INT [])

问题描述:

我已经看到了问题:如何创建的ArrayList(ArrayList的< T>从数组)(T [])

然而,当我尝试用以下code,它的解决方案,它在所有的情况下,不是那么回事:

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);
    }
}

我在做什么错在这里?应该不是code intList中=新的ArrayList&LT;整数GT;(Arrays.asList(intArray)); 编译就好了

在问题

intList = new ArrayList<Integer>(Arrays.asList(intArray));

INT [] 是因为基本数组从对象实例$ C>对象。如果你有这工作整数[] 而不是 INT [] ,因为现在你发送的数组对象

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));

但既然你已经在使用循环,我不介意使用一个临时包装类数组,只需直接添加项目到列表:

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);
}