簡體   English   中英

Java:將字節列表轉換為字節數組

[英]Java : convert List of Bytes to array of bytes

試圖解決什么應該是一個簡單的問題。 得到一個字節列表,想在函數末尾將它轉換為字節數組。

final List<Byte> pdu = new ArrayList<Byte>();
....
return pdu.toArray(new byte[pdu.size()]);;

編譯器不喜歡我的toArray上的語法。 如何解決這個問題?

編譯器不喜歡它,因為byte[]不是Byte[]

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

Byte[] bytes = pdu.toArray(new Byte[pdu.size()]);
return ArrayUtils.toPrimitive(bytes);

如果您不能使用 commons-lang,只需遍歷數組並用值填充另一個byte[]類型的數組(它們將自動拆箱)

如果您可以使用Byte[]而不是byte[] - 就這樣吧。

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

List<Byte> list = ...
byte[] bytes = Bytes.toArray(list);

這使您不必執行 Commons Lang 等效項要求您自己進行的中間數組轉換。

主要是,您不能將原始類型與toArray(T[])

請參閱: 如何在 Java 中將 List<Integer> 轉換為 int[]? . 這與應用於整數的問題相同。

也試試美元檢查這個修訂版):

import static com.humaorie.dollar.Dollar.*
...

List<Byte> pdu = ...;
byte[] bytes = $(pdu).convert().toByteArray();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM