Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behaviour in serialization

I have the following code:

ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("test.dat"));
ArrayList<String> list = null;
for(int i = 0; i < 10; i++)
{
    list = new ArrayList<String>();
    list.add("Object" + i);
    oo.writeObject(list);
}
oo.close();

When I open the test.dat file and unserialize the objects, I get all the objects. But if I change my code to this:

ObjectOutputStream oo = new ObjectOutputStream(new FileOutputStream("test.dat"));
ArrayList<String> list = new ArrayList<String>();
for(int i = 0; i < 10; i++)
{
    list.clear(); //clear the earlier objects
    list.add("Object" + i);
    oo.writeObject(list);
}
oo.close();

Now when I read the objects, I only get the first one i.e. Object0. Can anyone please explain the behavior?

like image 998
Swaranga Sarma Avatar asked Jul 18 '26 03:07

Swaranga Sarma


1 Answers

When you write an object to an ObjectOutputStream twice, then the second time will just be written as a reference to the original data ("that ArrayList with id x that I wrote before").

This happens even if the content of the object has changed (as it does in your case), therefore you will only have 1 full serialization (the first one) and 9 references to that in the second case.

You could call ObjectOutputStream.reset() to discard the list of previously written objects and force it to do a full serialization again.

like image 104
Joachim Sauer Avatar answered Jul 19 '26 18:07

Joachim Sauer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!