Java:将字节列表转换为字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3176222/
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
Java : convert List of Bytes to array of bytes
提问by fred basset
Trying to solve what should be a simple problem. Got a list of Bytes, want to convert it at the end of a function to an array of bytes.
试图解决什么应该是一个简单的问题。得到一个字节列表,想在函数末尾将它转换为字节数组。
final List<Byte> pdu = new ArrayList<Byte>();
....
return pdu.toArray(new byte[pdu.size()]);;
compiler doesn't like syntax on my toArray
. How to fix this?
编译器不喜欢我的toArray
. 如何解决这个问题?
采纳答案by Bozho
The compiler doesn't like it, because byte[]
isn't Byte[]
.
编译器不喜欢它,因为byte[]
不是Byte[]
.
What you can do is use commons-lang's ArrayUtils.toPrimitive(wrapperCollection)
:
你可以做的是使用commons-lang的ArrayUtils.toPrimitive(wrapperCollection)
:
Byte[] bytes = pdu.toArray(new Byte[pdu.size()]);
return ArrayUtils.toPrimitive(bytes);
If you can't use commons-lang, simply loop through the array and fill another array of type byte[]
with the values (they will be automatically unboxed)
如果您不能使用 commons-lang,只需循环遍历数组并byte[]
用值填充另一个类型的数组(它们将自动拆箱)
If you can live with Byte[]
instead of byte[]
- leave it that way.
如果你可以忍受Byte[]
而不是byte[]
- 就这样吧。
回答by Kru
Mainly, you cannot use a primitive type with toArray(T[])
.
主要是,您不能将原始类型与toArray(T[])
.
See: How to convert List<Integer> to int[] in Java?. This is the same problem applied to integers.
请参阅:如何在 Java 中将 List<Integer> 转换为 int[]?. 这与应用于整数的问题相同。
回答by ColinD
Use Guava's method Bytes.toArray(Collection<Byte> collection).
使用Guava的方法Bytes.toArray(Collection<Byte> collection)。
List<Byte> list = ...
byte[] bytes = Bytes.toArray(list);
This saves you having to do the intermediate array conversion that the Commons Lang equivalent requires yourself.
这使您不必执行 Commons Lang 等效项要求您自己进行的中间数组转换。
回答by dfa
try also Dollar(check this revision):
import static com.humaorie.dollar.Dollar.*
...
List<Byte> pdu = ...;
byte[] bytes = $(pdu).convert().toByteArray();