Skip to content
Advertisement

Java : convert List of Bytes to array of bytes

Trying to solve what should be a simple problem. Got a list of Bytes, want to convert it at the end of a function to an array of bytes.

final List<Byte> pdu = new ArrayList<Byte>();
....
return pdu.toArray(new byte[pdu.size()]);;

compiler doesn’t like syntax on my toArray. How to fix this?

Advertisement

Answer

The compiler doesn’t like it, because byte[] isn’t Byte[].

What you can do is use commons-lang‘s ArrayUtils.toPrimitive(wrapperCollection):

Byte[] bytes = pdu.toArray(new Byte[pdu.size()]);
return ArrayUtils.toPrimitive(bytes);

If you can’t use commons-lang, simply loop through the array and fill another array of type byte[] with the values (they will be automatically unboxed)

If you can live with Byte[] instead of byte[] – leave it that way.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement