Sending the same but modifed object over ObjectOutputStream

余生长醉 提交于 2019-11-26 15:31:01

The stream has a reference graph, so an object which is sent twice will not give two objects on the other end, you will only get one. And sending the same object twice separately will give you the same instance twice (each with the same data - which is what you're seeing).

See the reset() method if you want to reset the graph.

Max is correct, but you can also use:

public void writeUnshared(Object obj);

See comment below for caveat

What you probably want is:

ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
List same = new ArrayList();
same.add(0);
oos.writeObject(same);
oos.flush();  // flush the stream here
same.clear();
same.add(1);
oos.writeObject(same);

Otherwise the same object will be flushed twice when the stream is closed or its buffer runs out.

Just FYI, when you deserialize the objects into, let's say o1 and o2, o1 != o2.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!