views:

158

answers:

3

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[] ?

+4  A: 

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.

Jon Skeet
Thank you! Very good answer!
Marthin
+3  A: 

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));
Bozho
Upvoted for giving Commons Lang as a solution, it has a utility method for pretty much everything you can think of.
ponzao
Thank you for that!
Marthin
A: 

Rather then including apache-commons for only this single method call, you can use Integer[] .

@Bozho , thanks mate for this suggestion.

Paarth