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;
}
stkent
  • 19,772
  • 14
  • 85
  • 111
The Student
  • 27,520
  • 68
  • 161
  • 264

4 Answers4

36

No, there is no such method in the JDK.

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

Ian Roberts
  • 120,891
  • 16
  • 170
  • 183
Joachim Sauer
  • 302,674
  • 57
  • 556
  • 614
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();
YoYo
  • 9,157
  • 8
  • 57
  • 74
  • 3
    you can also: `List boxedList = IntStream.of(ints).boxed().collect(Collectors.toList())` – juanmf Jul 01 '17 at 16:09
  • @juanmf correct, but that does not answer the post directly: a `List` is not an `Integer []` as is requested for a boxed _array_. – YoYo Oct 02 '17 at 02:28
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);
Nacho
  • 1,104
  • 1
  • 13
  • 30
bodmas
  • 41
  • 2
  • 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. – YoYo Jan 10 '17 at 22:01
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.

Dragas
  • 1,140
  • 13
  • 29