27

Possible Duplicate:
How to convert an ArrayList containing Integers to primitive int array?

How to convert an ArrayList<Byte> into a byte[]?

ArrayList.toArray() gives me back a Byte[].

Community
  • 1
  • 1
fulmicoton
  • 15,502
  • 9
  • 54
  • 74
  • 14
    ArrayList is about the most inefficient way to store Bytes there is. If you don't know how many bytes to will have using ByteArrayOutputStream with write() and toByteArray(), don't use List if you can avoid it at all. – Peter Lawrey Jul 28 '11 at 15:55

4 Answers4

17
byte[] result = new byte[list.size()];
for(int i = 0; i < list.size(); i++) {
    result[i] = list.get(i).byteValue();
}

Yeah, Java's collections are annoying when it comes to primitive types.

meisterluk
  • 804
  • 10
  • 19
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
9

After calling toArray() you can pass the result into the Apache Commons toPrimitive method:

https://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/ArrayUtils.html#toPrimitive-java.lang.Byte:A->

JustinKSU
  • 4,875
  • 2
  • 29
  • 51
8

No built-in method comes to mind. However, coding one up is pretty straightforward:

public static byte[] toByteArray(List<Byte> in) {
    final int n = in.size();
    byte ret[] = new byte[n];
    for (int i = 0; i < n; i++) {
        ret[i] = in.get(i);
    }
    return ret;
}

Note that this will give you a NullPointerException if in is null or if it contains nulls. It's pretty obvious how to change this function if you need different behaviour.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2
byte[] data = new byte[list.size()];
for (int i = 0; i < data.length; i++) {
    data[i] = (byte) list.get(i);
}

Please note that this can take some time due to the fact that Byte objects needs to be converted to byte values.

Also, if your list contains null values, this will throw a NullPointerExcpetion.

Vivien Barousse
  • 20,555
  • 2
  • 63
  • 64