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

4

32

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;
}
Harlin answered 6/4, 2010 at 15:3 Comment(2)
Out of curiosity, why do you want to create an array of boxed values?Celinacelinda
Probably to use them in a list or another data structure, because java does not permit primitive generics.Keynesianism
B
37

No, there is no such method in the JDK.

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

Bonheur answered 6/4, 2010 at 15:4 Comment(0)
M
25

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();
Moderator answered 4/6, 2015 at 5:49 Comment(2)
you can also: List<Integer> boxedList = IntStream.of(ints).boxed().collect(Collectors.toList())Pamilapammi
@Pamilapammi correct, but that does not answer the post directly: a List<Integer> is not an Integer [] as is requested for a boxed array.Moderator
A
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);
Arborvitae answered 1/4, 2016 at 18:2 Comment(1)
I have seen this solution several times - and in my guts it does not seem like a clean solution (the way you bring in a non-enclosed variable). However I do not seem to find a real good argument against it.Moderator
K
1

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.

Keynesianism answered 25/11, 2018 at 9:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.