Alex Rivera | Logout

Most concise way to insert array of bytes into List<Byte>?

Asked 2010-08-20T16:21:23.663
18

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);
    }
}
Edit
Report

1 Answer

27

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

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

So you have two choices:

  • 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
    • With Guava can convert byte[] immediatelly to List<Byte>

The first option looks like this:

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

The second option with Guava looks like this:

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

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

answered 2010-08-20T16:36:11.203

Your Answer