Reputation: 6152
I have a question about the semantics of Java serialization: does deserializing the same object twice actually create two instances in memory? For instance:
ByteArrayOutputStream ba = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(ba);
LinkedListNode tail = new LinkedListNode(null);
LinkedListNode n1 = new LinkedListNode(tail);
oos.writeObject(n1);
oos.flush();
ByteArrayInputStream bi = new ByteArrayInputStream(ba.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bi);
LinkedListNode r1 = (Node)ois.readObject();
ByteArrayInputStream bi2 = new ByteArrayInputStream(ba.toByteArray());
ObjectInputStream ois2 = new ObjectInputStream(bi2);
LinkedListNode r2 = (Node)ois2.readObject();
System.out.println("r1 == r2 " + (r1 == r2)); // prints false
System.out.println("r1.next == r2.next " + (r1.next == r2.next)); // prints false
The code seems to imply that the answer is yes. I am wondering if this behavior makes sense?
Upvotes: 1
Views: 2308