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 you have a
Byte[] arr— an array of reference types — you can useArrays.asList(arr)to get aList<Byte>.IF you have a
byte[] arr— an array of primitives — you can’t useArrays.asList(arr)to get aList<Byte>. Instead you’ll get a one-elementList<byte[]>.So you have two choices:
byteinbyte[]andaddindividuallybyte[]toByte[]Arrays.asListandaddAllbyte[]immediatelly toList<Byte>The first option looks like this:
The second option with Guava looks like this:
This uses
Bytes.asListfrompackage com.google.common.primitives. The package has other conversion utilities for other primitives too. The entire library is highly useful.With Apache Commons Lang, you can use
Byte[] toObject(byte[])fromArrayUtils:Related questions
int[]intoList<Integer>in Java?Arrays.asList()not working as it should?