| Author |
About Object Serialization (Confusion)
|
gunjan bohra
Ranch Hand
Joined: Mar 24, 2004
Posts: 40
|
|
Consider the following code segment: ObjectOutputStream out = new ObjectOutputStream(...); MyObject obj = new MyObject(); //MyObject class is serializable obj.setState(100); out.writeObject(obj); obj.setState(200); out.writeObject(obj); What is the final value of the field "state" in the serialized form? It's an 100 then why?
|
 |
William Brogden
Author and all-around good cowpoke
Rancher
Joined: Mar 22, 2000
Posts: 12268
|
|
It looks to me like you wrote 2 copies to out, the first with 100, the second with 200. Bill
|
 |
gunjan bohra
Ranch Hand
Joined: Mar 24, 2004
Posts: 40
|
|
Ya offcourse ..and when i got back .I will got the first one means 100 Why it's so ?
|
 |
William Brogden
Author and all-around good cowpoke
Rancher
Joined: Mar 22, 2000
Posts: 12268
|
|
Why it's so ?
I don't understand the source of your confusion. An ObjectOutputStream can be used to write one or many Serializable objects. Bill
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
Serialization doesn't write data, it writes objects. What gets written to your stream are two references to the same object. The second reference will not include the object's member data, because the serialization mechanism remembers which objects have already been written out, and by default won't write their data a second time, even if that data has changed. If an object has already been written, and you want to write a second copy including the values of all the member variables as if the second copy were an altogether separate object, you have to call reset() on the ObjectOutputStream to tell it to forget about any previously-written objects.
|
[Jess in Action][AskingGoodQuestions]
|
 |
 |
|
|
subject: About Object Serialization (Confusion)
|
|
|