Marthin
Marthin

Reputation: 6543

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

Upvotes: 2

Views: 943

Answers (3)

Parth
Parth

Reputation: 1281

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

@Bozho , thanks mate for this suggestion.

Upvotes: 0

Bozho
Bozho

Reputation: 597432

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));

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1504122

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.

Upvotes: 4

Related Questions