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
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==o2returns false while (if you implement reasonableequals()method)o1.equals(o2)returns true.