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?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
CSchulz
  • 10,882
  • 11
  • 60
  • 114
  • possible duplicate of [How to convert an ArrayList containing Integers to primitive int array?](http://stackoverflow.com/questions/718554/how-to-convert-an-arraylist-containing-integers-to-primitive-int-array) – Ciro Santilli OurBigBook.com Mar 26 '15 at 14:09

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
  • 53,625
  • 36
  • 139
  • 164
2

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

Thomas
  • 87,414
  • 12
  • 119
  • 157
  • 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
  • 7,099
  • 23
  • 28