2

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

2
  • what do you need it for? Collections are best kept as Collection classes... unless there is a need to optimise, but then you have to be sure that you are not optimising prematurely (an ArrayList is almost as fast an an array) Commented May 20, 2010 at 11:05
  • Thats correct, but in this case I need to have a int[] to return for another function that only takes int[]. (not built by me) Commented May 20, 2010 at 11:36

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

Upvoted for giving Commons Lang as a solution, it has a utility method for pretty much everything you can think of.
0

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

@Bozho , thanks mate for this suggestion.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.