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

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

当前回答

谷歌番石榴

谷歌Guava通过调用int . toarray提供了一种简洁的方法。

List<Integer> list = ...;
int[] values = Ints.toArray(list);

其他回答

Integer[] arr = (Integer[]) x.toArray(new Integer[x.size()]);

像正常int[]一样访问arr。

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

使用Dollar应该非常简单:

List<Integer> list = $(5).toList(); // the list 0, 1, 2, 3, 4  
int[] array = $($(list).toArray()).toIntArray();

我计划改进DSL,以删除中间的toArray()调用

一个非常简单的解决方案是:

Integer[] i = arrlist.stream().toArray(Integer[]::new);

如果您正在使用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集合的提交者。