3

I use an ArrayList with the wrapper class Short.
After adding some values I want to get the primitive array, but it seems that there is no way with the function toArray(Object[] array), because it need an Array with the wrapper class.

Is there another way without using a for or anything like that?

1

3 Answers 3

5

Apache Commons / Lang has a class ArrayUtils that defines these methods.

  • All methods called toObject() convert from primitive array to wrapper array.
  • All called toPrimitive() convert from wrapper object array to primitive array

I think, you need ArrayUtils's toPrimitive()

public static short[] toPrimitive(Short[] array)

Converts an array of object Shorts to primitives.

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

Comments

2

Try org.apache.commons.lang.ArrayUtils's toPrimitive(...) method.

1 Comment

Just be careful with this, since you are copying array two times: first time with toArray() and second time with toPrimitive(). None of them returns underlying array.
1

You can fill the array yourself:

ArrayList<Short> shorts = ...;
short shortArray[] = new short[shorts.size()];
for (int i = 0; i < shorts.size(); i++)
   shortArray[i] = shorts.get(i);

Notice that I exploit autoboxing in the assignment line.

6 Comments

You could use a library as others suggest, but that seems a bit of an overkill to avoid writing three lines of code.
He wanted a solution without a for loop.
@phlogratos: He doesn't state that anywhere. Also, a library would of course use a for loop in the same way as above, so the loop is just pushed into some library function.
He wrote: Is there another way without using a for or anything like that?
Ok, I must have misread that sentence. The answer to his question is basically that he needs a for loop, either in a library function or written directly.
|

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.