Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a single object written to two different Streams represent two distinct objects when read back?

The title tells my need and here the following is code that I'm use:

Test Case

SameObjectDifferentStreams same = new SameObjectDifferentStreams(); 
ObjectOutputStream out1 = new ObjectOutputStream(new FileOutputStream("file1"));
ObjectOutputStream out2 = new ObjectOutputStream(new FileOutputStream("file2"));

out1.writeObject(same);
out1.close();

out2.writeObject(same);
out2.close();

System.out.println("The Original reference is :" + same.toString());

oin1 = new ObjectInputStream(new FileInputStream("file1"));
oin2 = new ObjectInputStream(new FileInputStream("file2"));

SameObjectDifferentStreams same1 = 
    (SameObjectDifferentStreams) oin1.readObject();
System.out.println("The First Instance is :" + same1.toString());

SameObjectDifferentStreams same2 = 
    (SameObjectDifferentStreams) oin2.readObject();
System.out.println("The Second Instance is :" + same2.toString());

Output

The Original reference is :serialization.SameObjectDifferentStreams@9304b1
The First Instance is :serialization.SameObjectDifferentStreams@190d11
The Second Instance is :serialization.SameObjectDifferentStreams@a90653
like image 767
Rekha Avatar asked Dec 05 '22 19:12

Rekha


1 Answers

When you write object to stream you actually serialize it, i.e. write its data only. Then when you read it you read the data and create new object. It is like if you invoke new MyObject() with appropriate constructor arguments. Obviously the new object is created here.

If you read the same serialized object twice you create new instance twice. These 2 instances are equal, i.e. all their fields are equal, but the references are different, so the expression o1==o2 returns false while (if you implement reasonable equals() method) o1.equals(o2) returns true.

like image 172
AlexR Avatar answered Mar 13 '23 01:03

AlexR