I'm looking to convert an ArrayList of bytes to byte[] in order to create a file with these bytes later. I've searched high and low on how to do this but still cant get my head around it. How can this be done?
4 Answers
There is no such thing as an ArrayList<byte>. When you declare one, you get an ArrayList<Byte>. So there's no single function idiom for turning this into byte[]. You'll have to allocate the byte[] and then write a loop to copy the values.
Or, you could use the fastutil library which does have a container like ArrayList that stores byte and which can yield an array.
2 Comments
ArrayList<Byte> in = ...;
int n = in.size();
byte[] out = new byte[n];
for (int i = 0; i < n; i++) {
out[i] = in.get(i);
}
I don't think the standard library provides any shortcuts for the above, provided you need byte[] and not Byte[].
2 Comments
If you have access to Guava, it's just Bytes.toArray(byteList). (Disclosure: I contribute to Guava.)
Comments
The function toArray should work, I don't hav ethe possibility to test it though..
ArrayList<Byte> listArray = new ArrayList<Byte>();
listArray.add((byte)1);
listArray.add((byte)2);
listArray.add((byte)3);
Byte[] myArray = new Byte[3];
listArray.toArray(myArray);
I don't know if the boxing would be a problem for you though, if you want to use it when writing to a file.