微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将任意维度的基元数组转换为其装箱对应物

如何解决如何将任意维度的基元数组转换为其装箱对应物

如果我有一个数组,例如

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#toObjectClassUtils#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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。