开发者

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

Is there a standard method I can use in place 开发者_Python百科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;
}


No, there is no such method in the JDK.

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


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();


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);


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.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜