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

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

当前回答

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

使用Apache Commons即可

其他回答

谷歌番石榴

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

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

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

这个代码段是为我工作,试试这个:

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

值得一提的是,数组列表应该这样声明:

ArrayList<Integer> list = new ArrayList<>();

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

使用Apache Commons即可