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;
}
When looking into Apache Commons Lang source code, we can see that it just calls
Byte#valueOf(byte)
on each array element.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.
Enter Java 8, and you can do following (boxing):
However, this only works for
int[]
,long[]
, anddouble[]
. This will not work forbyte[]
.You can also easily accomplish the reverse (unboxing)
In addition to YoYo's answer, you can do this for any primitive type; let
primArray
be an identifier of typePrimType[]
, then you can do the following:No, there is no such method in the JDK.
As it's often the case, however, Apache Commons Lang provides such a method.