Win a copy of Java 9 Revealed this week in the Features new in Java 9 forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Serialization of strings  RSS feed

 
Chris Brady
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Chris Brady
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think I found the answer. Here is the code to test it:



The result is:
Same string object
Same string object
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24216
37
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!