How does serialization work when an object has multiple references to the same String object?
If serializable Object1 has references to serializable objects Object2 and Object3, and both Object2 and Object3 have a reference to String1, how many copies of String1 exist when Object1 is serialized and then deserialized? Is it still just one String object, or is it now two String objects with the same value?
posted 13 years ago
I think I found the answer. Here is the code to test it:
The result is: Same string object Same string object
This is true for all objects. An ObjectOutputStream keeps track of every object it writes. If it's asked to write an object a second or later time, it doesn't; instead, it writes a record that means "that same object over there, again." This is a source of frustration sometimes: if you write an object, change it, and write it again, then when the Stream is read, you read out two copies of the first state of the object.