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

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

当前回答

如果您正在使用Eclipse Collections,您可以使用collectInt()方法从对象容器切换到原始int容器。

List<Integer> integers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
MutableIntList intList =
  ListAdapter.adapt(integers).collectInt(i -> i);
Assert.assertArrayEquals(new int[]{1, 2, 3, 4, 5}, intList.toArray());

如果可以将数组列表转换为FastList,就可以摆脱适配器。

Assert.assertArrayEquals(
  new int[]{1, 2, 3, 4, 5},
  Lists.mutable.with(1, 2, 3, 4, 5)
    .collectInt(i -> i).toArray());

注意:我是Eclipse集合的提交者。

其他回答

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

使用Apache Commons即可

我相信使用List的迭代器迭代是一个更好的主意,因为List .get(I)可能会有很差的性能,这取决于List的实现:

private int[] buildIntArray(List<Integer> integers) {
    int[] ints = new int[integers.size()];
    int i = 0;
    for (Integer n : integers) {
        ints[i++] = n;
    }
    return ints;
}

Java 8

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

OR 

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

Arrays.setAll ()

    List<Integer> x = new ArrayList<>(Arrays.asList(7, 9, 13));
    int[] n = new int[x.size()];
    Arrays.setAll(n, x::get);

    System.out.println("Array of primitive ints: " + Arrays.toString(n));

输出:

原始整数数组:[7,9,13]

这同样适用于long或double类型的数组,但不适用于boolean、char、byte、short或float类型的数组。如果您有一个非常大的列表,甚至可以使用parallelSetAll方法来代替。

对我来说,这是足够好的和优雅的,我不想获得一个外部库或使用流。

文档链接:数组。setAll (int [], IntUnaryOperator)

Apache Commons有一个ArrayUtils类,它有一个方法toPrimitive()来完成这个任务。

import org.apache.commons.lang.ArrayUtils;
...
    List<Integer> list = new ArrayList<Integer>();
    list.add(new Integer(1));
    list.add(new Integer(2));
    int[] intArray = ArrayUtils.toPrimitive(list.toArray(new Integer[0]));

然而,正如Jon所展示的,自己做这件事非常容易,而不是使用外部库。