Java:将字节列表转换为字节数组

fre*_*set 29 java arrays collections

试图解决什么应该是一个简单的问题.有一个Bytes列表,想要在函数末尾将它转换为字节数组.

final List<Byte> pdu = new ArrayList<Byte>();
....
return pdu.toArray(new byte[pdu.size()]);;
Run Code Online (Sandbox Code Playgroud)

编译器不喜欢我的语法toArray.如何解决这个问题?

Boz*_*zho 46

编译器不喜欢它,因为byte[]不是Byte[].

你可以做的是使用commons-langArrayUtils.toPrimitive(wrapperCollection):

Byte[] bytes = pdu.toArray(new Byte[pdu.size()]);
return ArrayUtils.toPrimitive(bytes);
Run Code Online (Sandbox Code Playgroud)

如果你不能使用commons-lang,只需循环遍历数组并byte[]用值填充另一个类型的数组(它们将自动取消装箱)

如果你可以忍受Byte[]而不是byte[]- 保持这种方式.

  • 我不喜欢 ArrayUtils 的解决方案。Java 8 必须有开箱即用的解决方案。 (4认同)

Col*_*inD 22

使用Guava的方法Bytes.toArray(Collection <Byte> collection).

List<Byte> list = ...
byte[] bytes = Bytes.toArray(list);
Run Code Online (Sandbox Code Playgroud)

这可以节省您必须进行Commons Lang等效的中间数组转换.


Kru*_*Kru 5

主要是,您不能将原始类型与toArray(T[]).

请参阅:如何在 Java 中将 List<Integer> 转换为 int[]?。这与应用于整数的问题相同。