Convert ArrayList into a byte[] [duplicate]

2020-02-10 12:07发布

问题:

This question already has answers here:
Closed 8 years ago.

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[].

回答1:

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

http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/ArrayUtils.html#toPrimitive(java.lang.Byte[])>



回答2:

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.



回答3:

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.



回答4:

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.