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?.
Unfortunately, I don't believe there really is a better way of doing this due to the nature of Java's handling of primitive types, boxing, arrays and generics. In particular:
List<T>.toArray
won't work because there's no conversion from Integer
to int
int
as a type argument for generics, so it would have to be an int
-specific method (or one which used reflection to do nasty trickery).I believe there are libraries which have autogenerated versions of this kind of method for all the primitive types (i.e. there's a template which is copied for each type). It's ugly, but that's the way it is I'm afraid :(
Even though the Arrays
class came out before generics arrived in Java, it would still have to include all the horrible overloads if it were introduced today (assuming you want to use primitive arrays).