开发者

Cast ArrayList of wrappers to corresponding array of primitives

开发者 https://www.devze.com 2023-03-19 13:45 出处:网络
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 to开发者_Go百科Array(Object[] array), b

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 to开发者_Go百科Array(Object[] array), because it need an Array with the wrapper class.

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


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消