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

2019-01-23 23:53发布

问题:

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

回答1:

No, there is no such method in the JDK.

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



回答2:

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


回答3:

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


回答4:

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.



标签: java boxing