Convert ArrayList<Byte> into a byte[] [duplicate]
Possible Duplicate:
How to convert an ArrayList containing Integers to primitive in开发者_如何学Ct array?
How to convert an ArrayList<Byte>
into a byte[]
?
ArrayList.toArray()
gives me back a Byte[]
.
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.
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->
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.
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
.
精彩评论