fre*_*set 29 java arrays collections
试图解决什么应该是一个简单的问题.有一个Bytes列表,想要在函数末尾将它转换为字节数组.
final List<Byte> pdu = new ArrayList<Byte>();
....
return pdu.toArray(new byte[pdu.size()]);;
编译器不喜欢我的语法toArray.如何解决这个问题?
Boz*_*zho 46
编译器不喜欢它,因为byte[]不是Byte[].
你可以做的是使用commons-lang的ArrayUtils.toPrimitive(wrapperCollection):
Byte[] bytes = pdu.toArray(new Byte[pdu.size()]);
return ArrayUtils.toPrimitive(bytes);
如果你不能使用commons-lang,只需循环遍历数组并byte[]用值填充另一个类型的数组(它们将自动取消装箱)
如果你可以忍受Byte[]而不是byte[]- 保持这种方式.
Col*_*inD 22
使用Guava的方法Bytes.toArray(Collection <Byte> collection).
List<Byte> list = ...
byte[] bytes = Bytes.toArray(list);
这可以节省您必须进行Commons Lang等效的中间数组转换.