Fastest way to convert ArrayList<Integer> into int[]
19,784
Solution 1
I cant think of any better solution than you have now with plain java. However if you use Guava, You can probably simplify it.
public convert(List<Integer> list) {
int[] ar = Ints.toArray(list); //Ints is the class from Guava library
}
Solution 2
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.
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.
int[] ints = new int[list.size()];
for(int i=0, len = list.size(); i < len; i++)
ints[i] = list.get(i);
Solution 3
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
Comments
-
Sophie Sperner almost 2 years
Possible Duplicate:
How to convert List<Integer> to int[] in Java?In Java, is below the fastest solution:
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(); } }
?
-
Jeffrey over 11 yearsThe OP is looking for an
int[]
, not anInteger[]
. -
Pramod Kumar over 11 yearsYou can do everything with Integer what you can do with int. thats why i posted it
-
Brian J over 11 yearsI don't know the answer off hand, but is a foreach loop any faster/better/different from a regular for loop? I thought it was the same thing, with an easier way to write it.
-
thermz over 11 yearsThe OP asks the question starting the problem with an
ArrayList<Integer>
, in your solution you do not consider the time you spend to trasform anArrayList<Integer>
to aTIntArrayList
. -
G. Bach over 11 yearsWhat is a "regular loop"? EDIT: ah I see, the advantage of the foreach- over the for-loop is that it probably uses an iterator instead of indices to access the list, thus not relying on the list providing get(i) in O(1). See stackoverflow.com/questions/85190/… on how a foreach-loop works.
-
Sophie Sperner over 11 yearsThe reason of using ArrayList at the start is that I do not know how much elements it will contain, once I filled in the ArrayList<Integer>, I need a copy for further speedup.
-
Harmeet Singh over 11 years@BrianJ here you go
-
Vishy over 11 yearsTIntArrayList can be any size. Why do you need a copy?
-
Sophie Sperner over 11 yearsWhat is
TIntArrayList
? -
Vishy over 11 yearstrove4j.sourceforge.net/javadocs/gnu/trove/list/array/… If you don't want to include an additional library, its trivial to implement.
-
Brian J over 11 years@G.Bach Thanks for the information!
-
Brian J over 11 years@HarmeetSingh Thanks for the information!
-
Jeffrey over 11 yearsExcept perform any arbitrary calculation without a loss of performance.