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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 07:03:40  来源:igfitidea点击:

Fastest way to convert ArrayList<Integer> into int[]

javaarraysarraylistint

提问by Sophie Sperner

Possible Duplicate:
How to convert List<Integer> to int[] in Java?

可能的重复:
如何在 Java 中将 List<Integer> 转换为 int[]?

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 TIntArrayListwhich wraps an int[], or use a int[]from the start.

最快的方法是首先不使用 an ArrayList<Integer>。试试TIntArrayListwhich 包装了一个 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-

I cant think of any better solution than you have now with plain java. However if you use Guava, You can probably simplify it.

我想不出比你现在使用普通 java 更好的解决方案。但是,如果您使用Guava,您可能可以简化它。

public convert(List<Integer> list) {
 int[] ar = Ints.toArray(list); //Ints is the class from Guava library
}

回答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()]);