3

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 4

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Its also incredibly inefficient to have an ArrayList[Byte] compared to a byte[]. Each element has an object pointer (4-8 bytes) + the Byte object overhead(12bytes) + the actual byte for the data. You really want to avoid this especially with a big array. This is how 40MB of data becomes 840MB in memory.
after further research I have found the following... codeglobe.blogspot.co.uk/2009/04/… would this solve my problem?
4
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

When I try and use this I get an imcompatible types error on the second from bottom line. required byte, Object found.
@user1286779 Only if you didn't copy the first line correctly.
2

If you have access to Guava, it's just Bytes.toArray(byteList). (Disclosure: I contribute to Guava.)

Comments

1

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.

1 Comment

The OP didn't ask for Byte[], but rather byte[].

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.