Is there a built-in Java method to box an array?

2019-01-23 23:17发布

Is there a standard method I can use in place of this custom method?

public static Byte[] box(byte[] byteArray) {
    Byte[] box = new Byte[byteArray.length];
    for (int i = 0; i < box.length; i++) {
        box[i] = byteArray[i];
    }
    return box;
}

标签: java boxing
4条回答
Juvenile、少年°
2楼-- · 2019-01-24 00:00

When looking into Apache Commons Lang source code, we can see that it just calls Byte#valueOf(byte) on each array element.

    final Byte[] result = new Byte[array.length];
    for (int i = 0; i < array.length; i++) {
        result[i] = Byte.valueOf(array[i]);
    }
    return result;

Meanwhile, regular java lint tools suggest that boxing is unnecessary and you can just assign elements as is.

So essentially you're doing the same thing apache commons does.

查看更多
干净又极端
3楼-- · 2019-01-24 00:02

Enter Java 8, and you can do following (boxing):

int [] ints = ...
Integer[] boxedInts = IntStream.of(ints).boxed().toArray(Integer[]::new);

However, this only works for int[], long[], and double[]. This will not work for byte[].

You can also easily accomplish the reverse (unboxing)

Integer [] boxedInts = ...
int [] ints = Stream.of(boxedInts).mapToInt(Integer::intValue).toArray();
查看更多
劳资没心,怎么记你
4楼-- · 2019-01-24 00:04

In addition to YoYo's answer, you can do this for any primitive type; let primArray be an identifier of type PrimType[], then you can do the following:

BoxedType[] boxedArray = IntStream.range(0, primArray.length).mapToObj(i -> primArray[i]).toArray(BoxedType[] :: new);
查看更多
不美不萌又怎样
5楼-- · 2019-01-24 00:15

No, there is no such method in the JDK.

As it's often the case, however, Apache Commons Lang provides such a method.

查看更多
登录 后发表回答