简体   繁体   English

从ArrayList创建一个int [] <Integer>

[英]Create an int[] from an ArrayList<Integer>

Is there an easy way of creating an int[] or the equivalent Integer[] from an ArrayList<Integer> ? 有没有一种简单的方法可以从ArrayList<Integer>创建int[]或等效的Integer[]

When I try (Integer[])list.getArray() , I get this stack trace: 当我尝试(Integer[])list.getArray() ,我得到了这个堆栈跟踪:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; 线程“主”中的异常java.lang.ClassCastException:[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer; 无法转换为[Ljava.lang.Integer;

The only other way I can think of is: 我能想到的唯一其他方法是:

int[] array = new int[list.size()];
for (int i = 0; i < array.size; i++){
    array[i] = list.get(i);
    //or I could do list.remove(0), is there any difference?
}
return array;

but that way seems terribly slow. 但是那样看来似乎很慢。

yourIntList.toArray(new Integer[yourIntList.size()]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM