1

I have an ArrayList with data that is my own custom object and I need to convert all of them into a byte array. I am able to convert the object to a byte array by serializing it but I need all the objects to be serialized into one array.

ArrayList<MyObject> myArrayList = new ArrayList<MyObject>();
// Getting a list of objects of database (any unknown number)
for(int counter = 0; counter < myObj.size(); counter++) {
    byte[] myData = serialize(myObj.get(counter));
}

Now how do I go about doing this for multiple objects as I do not know the length to initialize by byte array buffer?

1
  • 2
    Couldn't you just serialize the arraylist itself? Commented Mar 11, 2015 at 22:13

2 Answers 2

1

If you really wish to convert it into a single byte[] juste use the ByteArrayOutputStream and call the appropriate functions as you need them.

Although you also need to consider turning this byte[] into a proper List again.

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

2 Comments

I need just the byte array as I need to send that data to a ble device.
The given class can even write to a given output Stream directly, making it integrate smoothly - or you could write the data to the output stream directly without the need to make them a single byte array at all.
0

Preallocate an array

byte[][] data = new byte[myObj.size()][];
long size = 0;

Generate bytes

for(int counter = 0; counter < myObj.size(); counter++) {
    data[counter] = serialize(myObj.get(counter));
    size += data[counter].length;
}

Concat to a final buffer "allData":

byte[] allData = new byte[size];
long curs = 0;
for(int i = 0; i < data.length; i++) {
    int length = data[i].length;
    System.arraycopy(data[i], 0, allData, curs, length);
    curs += length;
}

Comments

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.