最简洁的方法是将字节数组插入List< Byte>? [英] Most concise way to insert array of bytes into 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 aByte
, abyte[]
DOES NOT get autoboxed toByte[]
!
(also true for other primitives)
所以你有两个选择:
- 在
byte []
和字节
>单独添加 - 使用库
- 使用 Apache Commons Lang ,您可以将
byte []
转换为字节[]
- 您可以然后
Arrays.asList
和addAll
- Just iterate over each
byte
inbyte[]
andadd
individually - Use libraries
- With Apache Commons Lang, you can convert
byte[]
toByte[]
- You can then
Arrays.asList
andaddAll
第一个选项如下:
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
frompackage 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[])
fromArrayUtils
:// requires Apache Commons Lang byte[] arr = ...; list.addAll(Arrays.asList(ArrayUtils.toObject(arr)));
相关问题
- 如何转换
int []
进入列表<整数>
用Java? -
Arrays.asList()
无法正常工作? - 自动装箱的性能影响
- 最有用的免费第三方Java库?
- How to convert
int[]
intoList<Integer>
in Java? Arrays.asList()
not working as it should?- Performance impact of autoboxing
- Most useful free third party Java libraries?
Related questions
这篇关于最简洁的方法是将字节数组插入List< Byte>?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- You can then
- With Apache Commons Lang, you can convert
- 您可以然后
- 使用 Apache Commons Lang ,您可以将