Typecast a ArrayList.toArray() in Java to normal array
I'm having some trouble to do the 开发者_如何学运维following:
int[] tmpIntList = (int[])MyArrayList.toArray(someValue);
MyArrayList contains only numbers. I get a typecast error since ArrayList
only returns Object[]
but why isnt it possible to turn it into a int[]
?
An ArrayList
can't contain int
values, as it's backed by an Object[]
(even when appropriately generic).
The closest you could come would be to have an Integer[]
- which can't be cast to an int[]
. You have to convert each element separately. I believe there are libraries which implement these conversions for all the primitive types.
Basically the problem is that Java generics don't support primitive types.
ArrayUtils.toPrimitive(..)
will do the conversion between Integer[]
and int[]
, if you really need it. (apache commons-lang)
So:
int[] tmpIntList = ArrayUtils.toPrimitive(MyArrayList.toArray(someValue));
Rather then including apache-commons for only this single method call, you can use
Integer[]
.
@Bozho , thanks mate for this suggestion.
精彩评论