将最简单的字节数组插入List <Byte>?

fre*_*set 16 java list

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

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

pol*_*nts 26

如果你有一个Byte[] arr- 一系列的引用类型 - 你可以Arrays.asList(arr)用来获得一个List<Byte>.

如果你有一个byte[] arr- 一个基元数组 - 你不能Arrays.asList(arr)用来得到一个List<Byte>.相反,你会得到一个单元素List<byte[]>.

也就是说,虽然一个byte可以盒装的Byte,一个byte[] DOES NOT得到autoboxed来Byte[]!
(对于其他原语也是如此)

所以你有两个选择:

  • 只是遍历每个bytebyte[]add个别
  • 使用库
    • 使用Apache Commons Lang,您可以转换byte[]Byte[]
      • 你可以 Arrays.asListaddAll
    • 随着番石榴可以byte[]立即转换为List<Byte>

第一个选项如下所示:

byte[] arr = ...;
for (byte b : arr) {
    list.add(b);
}
Run Code Online (Sandbox Code Playgroud)

Guava的第二个选项如下:

// requires Guava
byte[] arr = ...;
list.addAll(Bytes.asList(arr));
Run Code Online (Sandbox Code Playgroud)

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

与Apache Commons Lang中,你可以使用Byte[] toObject(byte[])ArrayUtils:

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

相关问题