开发者

Different behaviour in serialization

I have the following开发者_Python百科 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?


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.


It's because in one case, you are using 10 object instances and in the other, you are using 1 instance. Your oo is only knowing 1 instance of the object to persist.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜