Different serialization behavior

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 the unserializeobjects, 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 objects, I get only the first, that is, Object0. Can someone explain the behavior?

+3
source share
2 answers

When you double-write an object in ObjectOutputStream, the second time it will simply be written as a reference to the source data ("this is ArrayListwith id x, which I wrote earlier").

This happens even if the contents of the object have changed (as in your case), so you will only have 1 full serialization (first) and 9 links to the contents in the second case.

ObjectOutputStream.reset(), .

+5

, 10 , - 1 . oo 1 .

0

All Articles