Cast ArrayList of wrappers to corresponding array of primitives
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 functionto开发者_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.
精彩评论