是否有内置的 Java 方法来装箱数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2585907/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a built-in Java method to box an array?
提问by Tom Brito
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;
}
采纳答案by Joachim Sauer
No, there is no such method in the JDK.
不,JDK 中没有这样的方法。
As it's often the case, however, Apache Commons Langprovides such a method.
然而,通常情况下,Apache Commons Lang提供了这样一种方法。
回答by YoYo
Enter Java 8, and you can do following (boxing):
进入Java 8,你可以做以下(装箱):
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[].
然而,这仅适用于int[],long[]和double[]。这对byte[].
You can also easily accomplish the reverse (unboxing)
您也可以轻松完成反向操作(拆箱)
Integer [] boxedInts = ...
int [] ints = Stream.of(boxedInts).mapToInt(Integer::intValue).toArray();
回答by bodmas
In addition to YoYo's answer, you can do this for anyprimitive type; let primArraybe an identifier of type PrimType[], then you cando the following:
除了 YoYo 的回答之外,您还可以对任何原始类型执行此操作;让primArray是 type 的标识符PrimType[],那么您可以执行以下操作:
BoxedType[] boxedArray = IntStream.range(0, primArray.length).mapToObj(i -> primArray[i]).toArray(BoxedType[] :: new);
回答by Dragas
When looking into Apache Commons Lang source code, we can see that it just calls Byte#valueOf(byte)on each array element.
在查看 Apache Commons Lang 源代码时,我们可以看到它只是调用Byte#valueOf(byte)每个数组元素。
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.
同时,常规的 java lint 工具表明不需要装箱,您可以按原样分配元素。
So essentially you're doing the same thing apache commons does.
所以基本上你在做 apache commons 做的同样的事情。

