最简洁的方法是将字节数组插入List< Byte>? [英] Most concise way to insert array of bytes into List<Byte>?

查看:119
本文介绍了最简洁的方法是将字节数组插入List< Byte>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在某些代码中,我正在创建一个Bytes列表,并希望在构建它时将一个字节数组插入到列表中。这样做最干净的方法是什么?请参阅下面的代码 - 谢谢。

In some code I'm creating a List of Bytes, and want to insert an array of bytes into the list as I am building it. What is the cleanest way of doing this? See code below - thanks.

public class ListInsert {
    public static byte[] getData() {
        return new byte[]{0x01, 0x02, 0x03};
    }

    public static void main(String[] args) {
        final List<Byte> list = new ArrayList<Byte>();
        list.add((byte)0xaa);
        list.add(getData()); // I want to insert an array of bytes into the list here
        list.add((byte)0x55);
    }
}


推荐答案

IF 你有一个 Byte [] arr - 一个引用类型数组 - 你可以使用 Arrays.asList(arr )获得列表<字节>

IF you have a Byte[] arr -- an array of reference types -- you can use Arrays.asList(arr) to get a List<Byte>.

IF 你有一个 byte [] arr - 一个基元数组 - 你不能使用 Arrays.asList(arr)获得列表<字节> 。相反,你将得到一个单元素列表< byte []>

IF you have a byte[] arr -- an array of primitives -- you can't use Arrays.asList(arr) to get a List<Byte>. Instead you'll get a one-element List<byte[]>.


也就是说,当字节可以装箱到字节时,字节[ ] 不会自动装箱到 Byte []

(也是如此对于其他原语)

That is, while a byte can be boxed to a Byte, a byte[] DOES NOT get autoboxed to Byte[]!
(also true for other primitives)

所以你有两个选择:


  • byte [] 字节 >单独添加

  • 使用库


    • 使用 Apache Commons Lang ,您可以将 byte [] 转换为字节[]


      • 您可以然后 Arrays.asList addAll

      • Just iterate over each byte in byte[] and add individually
      • Use libraries
        • With Apache Commons Lang, you can convert byte[] to Byte[]
          • You can then Arrays.asList and addAll

          第一个选项如下:

          byte[] arr = ...;
          for (byte b : arr) {
              list.add(b);
          }
          

          Guava的第二个选项如下:

          The second option with Guava looks like this:

          // requires Guava
          byte[] arr = ...;
          list.addAll(Bytes.asList(arr));
          

          这使用 Bytes.asList 来自 package com.google.common.primitives 。该包还具有其他原语的其他转换实用程序。整个库非常有用。

          This uses Bytes.asList from package com.google.common.primitives. The package has other conversion utilities for other primitives too. The entire library is highly useful.

          使用Apache Commons Lang,你可以使用 Byte [] toObject(byte []) 来自 ArrayUtils

          With Apache Commons Lang, you can use Byte[] toObject(byte[]) from ArrayUtils:

          // requires Apache Commons Lang
          byte[] arr = ...;
          list.addAll(Arrays.asList(ArrayUtils.toObject(arr)));
          



          相关问题



查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆