在某些代码中,我正在创建一个字节列表,并希望在构建它时将一个字节数组插入到该列表中。这样做最干净的方法是什么?请参阅下面的代码 - 谢谢。
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)
得到一个List<Byte>
.
IF你有一个byte[] arr
-- 基元数组 -- 你不能使用Arrays.asList(arr)
得到一个List<Byte>
。相反,你会得到一个单元素List<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
in byte[]
and add
单独地
- Use libraries
- With Apache Commons Lang http://commons.apache.org/lang/, you can convert
byte[]
to Byte[]
- You can then
Arrays.asList
and addAll
- With Guava http://guava-libraries.googlecode.com/可以转换
byte[]
立即到List<Byte>
第一个选项如下所示:
byte[] arr = ...;
for (byte b : arr) {
list.add(b);
}
Guava 的第二个选项如下所示:
// requires Guava
byte[] arr = ...;
list.addAll(Bytes.asList(arr));
这使用Bytes.asList http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/primitives/Bytes.html#asList%28byte...%29 from package com.google.common.primitives http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/primitives/package-summary.html。该包还具有用于其他原语的其他转换实用程序。整个图书馆非常有用。
通过 Apache Commons Lang,您可以使用Byte[] toObject(byte[]) http://commons.apache.org/lang/api-release/org/apache/commons/lang/ArrayUtils.html#toObject%28byte%5B%5D%29 from ArrayUtils
:
// requires Apache Commons Lang
byte[] arr = ...;
list.addAll(Arrays.asList(ArrayUtils.toObject(arr)));
相关问题
- 如何转换int[] into List<Integer>在Java中? https://stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java
- Arrays.asList()没有正常工作? https://stackoverflow.com/questions/1467913/arrays-aslist-not-working-as-it-should
- 自动装箱的性能影响 https://stackoverflow.com/questions/3430671/performance-impact-of-autoboxing/
- 最有用的免费第三方 Java 库? https://stackoverflow.com/questions/130095/most-useful-free-third-party-java-libraries
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)