Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 662
fred basset Avatar asked Jul 04 '10 21:07

fred basset


People also ask

How to convert List into byte array in Java?

Write the contents of the object to the output stream using the writeObject() method of the ObjectOutputStream class. Flush the contents to the stream using the flush() method. Finally, convert the contents of the ByteArrayOutputStream to a byte array using the toByteArray() method.

How to convert List to byte array in Java 8?

Make the Author class serializable and write the list to an ObjectOutputStream backed by a ByteArrayOutputStream . Show activity on this post. Make your class Serializable; create an ObjectStream over a ByteStream and write your list to the ObjectStream. Pass the byte buffer from the ByteStream to your caching API.

How do you convert a list to an array in Java?

The best and easiest way to convert a List into an Array in Java is to use the . toArray() method. Likewise, we can convert back a List to Array using the Arrays. asList() method.


1 Answers

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.

like image 134
Bozho Avatar answered Sep 20 '22 19:09

Bozho