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?

CSchulz
  • 10,542
  • 10
  • 57
  • 112

3 Answers3

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.

Saurabh Gokhale
  • 51,864
  • 34
  • 134
  • 163
2

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

Thomas
  • 84,542
  • 12
  • 116
  • 151
  • 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. – Op De Cirkel Jul 11 '11 at 11:34
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.

Mathias Schwarz
  • 6,939
  • 21
  • 28