【问题标题】:Java : convert List of Bytes to array of bytesJava:将字节列表转换为字节数组
【发布时间】:2011-03-11 17:05:40
【问题描述】:

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

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

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

【问题讨论】:

    标签: java arrays collections


    【解决方案1】:

    也可以试试Dollar (check this revision):

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

    【讨论】:

      【解决方案2】:

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

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

      这使您不必进行 Commons Lang 等效项需要您自己进行的中间数组转换。

      【讨论】:

        【解决方案3】:

        主要是,您不能将原始类型与toArray(T[]) 一起使用。

        请参阅:How to convert List<Integer> to int[] in Java?。 这与应用于整数的问题相同。

        【讨论】:

          【解决方案4】:

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

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

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

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

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

          【讨论】:

          • 非常感谢! :) 之前没见过 ArrayUtils.toPrimitive,挺有用的。
          • 我不喜欢 ArrayUtils 的解决方案。 Java 8 必须有现成的解决方案。
          猜你喜欢
          • 2011-07-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-10-17
          相关资源
          最近更新 更多