java 将 ArrayList<Integer> 转换为 int[] 的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11952516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fastest way to convert ArrayList<Integer> into int[]
提问by Sophie Sperner
Possible Duplicate:
How to convert List<Integer> to int[] in Java?
In Java, is below the fastest solution:
在 Java 中,低于最快的解决方案:
public convert(ArrayList<Integer> IntegerList) {
int s = IntegerList.size();
int[] intArray = new int[s];
for (int i = 0; i < s; i++) {
intArray[i] = IntegerList.get(i).intValue();
}
}
?
?
回答by Peter Lawrey
The fastest way is to not use an ArrayList<Integer>
in the first place. Try TIntArrayList
which wraps an int[], or use a int[]
from the start.
最快的方法是首先不使用 an ArrayList<Integer>
。试试TIntArrayList
which 包装了一个 int[],或者int[]
从一开始就使用 a 。
If you have to use an ArrayList for some reason and you can't fix it, you are need a way which works and performance is less important.
如果出于某种原因必须使用 ArrayList 并且无法修复它,则需要一种有效且性能不那么重要的方法。
int[] ints = new int[list.size()];
for(int i=0, len = list.size(); i < len; i++)
ints[i] = list.get(i);
回答by RP-
回答by Harmeet Singh
public void convert(ArrayList<Integer> IntegerList) {
int[] intArray = new int[IntegerList.size()];
int count = 0;
for(int i : IntegerList){
intArray[count++] = i;
}
}
UPDATE: Q. but is a foreach loop any faster/better/different from a regular for loop?
A. here
更新: 问:但是 foreach 循环是否比常规 for 循环更快/更好/不同?
A、这里
回答by Pramod Kumar
Integer[] intArray = IntegerList.toArray(new Integer[IntegerList.size()]);