我试图用下面的代码段将包含整数对象的数组列表转换为原始int[],但它抛出编译时错误。可以在Java中转换吗?

List<Integer> x =  new ArrayList<Integer>();
int[] n = (int[])x.toArray(int[x.size()]);

当前回答

Arrays.setAll()适用于大多数场景:

Integer List to primitive int array: public static int[] convert(final List<Integer> list) { final int[] out = new int[list.size()]; Arrays.setAll(out, list::get); return out; } Integer List (made of Strings) to primitive int array: public static int[] convert(final List<String> list) { final int[] out = new int[list.size()]; Arrays.setAll(out, i -> Integer.parseInt(list.get(i))); return out; } Integer array to primitive int array: public static int[] convert(final Integer[] array) { final int[] out = new int[array.length]; Arrays.setAll(out, i -> array[i]); return out; } Primitive int array to Integer array: public static Integer[] convert(final int[] array) { final Integer[] out = new Integer[array.length]; Arrays.setAll(out, i -> array[i]); return out; }

其他回答

让我困惑的是,当一个完美的、使用良好的库(如Apache Commons)已经解决了问题时,我们却鼓励一次性的自定义方法。尽管解决方案是微不足道的,但由于长期维护和可访问性,鼓励这种行为是不负责任的。

使用Apache Commons即可

这对我来说很好:)

网址:https://www.techiedelight.com/convert-list-integer-array-int/

import java.util.Arrays;
import java.util.List;

class ListUtil
{
    // Program to convert list of integer to array of int in Java
    public static void main(String args[])
    {
        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

        int[] primitive = list.stream()
                            .mapToInt(Integer::intValue)
                            .toArray();

        System.out.println(Arrays.toString(primitive));
    }
}

Java 8

int[] array = list.stream().mapToInt(i->i).toArray();

OR 

int[] array = list.stream().mapToInt(Integer::intValue).toArray();
   List<Integer> list = new ArrayList<Integer>();

    list.add(1);
    list.add(2);

    int[] result = null;
    StringBuffer strBuffer = new StringBuffer();
    for (Object o : list) {
        strBuffer.append(o);
        result = new int[] { Integer.parseInt(strBuffer.toString()) };
        for (Integer i : result) {
            System.out.println(i);
        }
        strBuffer.delete(0, strBuffer.length());
    }

你可以简单地将它复制到一个数组:

int[] arr = new int[list.size()];
for(int i = 0; i < list.size(); i++) {
    arr[i] = list.get(i);
}

不要太花哨;但是,嘿,它是有效的…