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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With