[...]
But do you have any answer to my second question?
Only that you're going about it wrong. As Andreas Leitgeb points
out, serializing an object is a different proposition than serializing
a bunch of "raw" values: It saves enough information to reconstruct an
"image" of the original object, with the same structure.
What do I mean by "structure?" Something like this:
Integer x = new Integer(42);
Integer y = new Integer(42);
Here we have two distinct Integer instances, each with the value 42.
ArrayList<Integer> one = new ArrayList<Integer>();
one.add(x);
one.add(x);
The first ArrayList holds one of the Integer instances, twice, and
has nothing to do with the other.
ArrayList<Integer> two = new ArrayList<Integer>();
two.add(x);
two.add(y);
The second ArrayList holds both Integer instances, once each.
If you serialize `one' and read it back again, you'll get an
ArrayList with two references to the same Integer. Reading it back
will produce one Integer, not two. There will be two objects in
the serialized stream: One ArrayList and one Integer, plus enough
additional information to reassemble them. (Actually, there will
probably be additional objects: The ArrayList owns an array, which
is an object in its own right, and perhaps there might be others.
But there'll be two "visible" objects in the stream.)
If you serialize `two' and read it back, you'll get an ArrayList
with two references to two distinct Integers: Three "visible" objects
in all.
It's all right to serialize an object graph and store it on disk.
It is *not* all right to try to update the serialization in place,
nor to modify the object and expect a re-serialization to have the
same size. If you need in-place operations or same-size guarantees,
you'll need to invent a different external representation for your data.