问题描述
int[][][] myArr = new int[][][] {{{1},{1,2,3}},{}};
如何将其转换为盒装对应物,即
Integer[][][] myArrBoxed = ...
解决方法
以下代码的使用:
int[][][] myArr = new int[][][] {{{1},{1,2,3}},{}};
Integer[][][] myArrBoxed = (Integer[][][]) boxArray(myArr);
此代码使用 Apache Commons Lang 来实现一些便利功能,特别是 ArrayUtils#toObject
和 ClassUtils#primitiveToWrapper
,以及一些较新的 Java 功能。不使用它们可以很容易地进行改造,尽管它会比现在更冗长。
/**
* Box an arbitrary-dimension primitive array
* @param arr an arbitrary-dimension primitive array,e.g.,an int[][][]
* @return arr,but boxed,an Integer[][][]
*/
public static Object boxArray(Object arr) {
return boxArray(arr,toWrapperArrayType(arr.getClass().getComponentType()));
}
private static Object boxArray(Object arr,Class<?> boxedType) {
if (arr instanceof int[])
return ArrayUtils.toObject((int[]) arr);
if (arr instanceof long[])
return ArrayUtils.toObject((long[]) arr);
if (arr instanceof double[])
return ArrayUtils.toObject((double[]) arr);
if (arr instanceof float[])
return ArrayUtils.toObject((float[]) arr);
if (arr instanceof short[])
return ArrayUtils.toObject((short[]) arr);
if (arr instanceof byte[])
return ArrayUtils.toObject((byte[]) arr);
if (arr instanceof char[])
return ArrayUtils.toObject((char[]) arr);
if (arr instanceof boolean[])
return ArrayUtils.toObject((boolean[]) arr);
if (!(arr instanceof Object[] objectArr))
throw new IllegalArgumentException("arr is not an array");
int length = Array.getLength(arr);
Object[] newArr = (Object[]) Array.newInstance(boxedType,length);
for (int i = 0; i < length; i++)
newArr[i] = boxArray(objectArr[i],boxedType.getComponentType());
return newArr;
}
/**
* Converts the type of an arbitrary dimension primitive array to it's wrapper type
* i.e. `toWrapperArrayType(int[][][].class) == Integer[][][].class`
*/
private static Class<?> toWrapperArrayType(Class<?> primitiveArrayType) {
int levels = 1;
Class<?> component = primitiveArrayType.getComponentType();
for (; component.isArray(); levels++)
component = component.getComponentType();
Class<?> boxedType = ClassUtils.primitiveToWrapper(component);
for (int i = 0; i < levels; i++)
boxedType = boxedType.arrayType();
return boxedType;
}