How can I convert a List<Integer>
to int[]
in Java?
I'm confused because List.toArray()
actually returns an Object[]
, which can be cast to neither Integer[]
nor int[]
.
Right now I'm using a loop to do so:
int[] toIntArray(List<Integer> list) {
int[] ret = new int[list.size()];
for(int i = 0; i < ret.length; i++)
ret[i] = list.get(i);
return ret;
}
Is there's a better way to do this?
This is similar to the question How can I convert int[] to Integer[] in Java?.
Integer[] arr = (Integer[])list.toArray(new Integer[list.size]);
– Tenacious