代码之家  ›  专栏  ›  技术社区  ›  fred basset

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

  •  29
  • fred basset  · 技术社区  · 16 年前

    试图解决一个简单的问题。得到一个字节列表,希望在函数末尾将其转换为一个字节数组。

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

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

    4 回复  |  直到 10 年前
        1
  •  42
  •   Bozho    16 年前

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

    你能做的就是利用 commons-lang 的 ArrayUtils.toPrimitive(wrapperCollection) :

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

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

    如果你能和 字节[] 而不是 字节[] -就这样吧。

        2
  •  19
  •   ColinD    16 年前

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

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

    这就省去了您必须执行commons-lang等价物所需的中间数组转换。

        3
  •  2
  •   Community Mohan Dere    9 年前

    主要是,不能将基元类型与 toArray(T[]) .

    见: How to convert List<Integer> to int[] in Java? . 这个问题同样适用于整数。

        4
  •  1
  •   dfa    16 年前

    也尝试 Dollar ( check this revision ):

    import static com.humaorie.dollar.Dollar.*
    ...
    
    List<Byte> pdu = ...;
    byte[] bytes = $(pdu).convert().toByteArray();