File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes About Object Serialization (Confusion) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "About Object Serialization (Confusion)" Watch "About Object Serialization (Confusion)" New topic
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: 12678
    
    5
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: 12678
    
    5
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: 24166
    
  30

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]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: About Object Serialization (Confusion)
 
Similar Threads
Data lost when writing object to a file
Using static
Not making Strings as null reference in static method has impcat on performace?
HTTP - tunneling and Objects..
Customize readObject and writeObject