简体   繁体   中英

Converting all objects in arraylist to byte array in java

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?

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM