Avoiding duplicate objects in Java deserialization

Posted by YGL on Stack Overflow See other posts from Stack Overflow or by YGL
Published on 2010-04-19T06:37:59Z Indexed on 2010/04/19 6:43 UTC
Read the original article Hit count: 213

I have two lists (list1 and list2) containing references to some objects, where some of the list entries may point to the same object. Then, for various reasons, I am serializing these lists to two separate files. Finally, when I deserialize the lists, I would like to ensure that I am not re-creating more objects than needed. In other words, it should still be possible for some entry of List1 to point to the same object as some entry in List2.

MyObject obj = new MyObject();
List<MyObject> list1 = new ArrayList<MyObject>();
List<MyObject> list2 = new ArrayList<MyObject>();
list1.add(obj);
list2.add(obj);

// serialize to file1.ser
ObjectOutputStream oos = new ObjectOutputStream(...);
oos.writeObject(list1);
oos.close();

// serialize to file2.ser
oos = new ObjectOutputStream(...);
oos.writeObject(list2);
oos.close();

I think that sections 3.4 and A.2 of the spec say that deserialization strictly results in the creation of new objects, but I'm not sure. If so, some possible solutions might involve:

  1. Implementing equals() and hashCode() and checking references manually.
  2. Creating a "container class" to hold everything and then serializing the container class.

Is there an easy way to ensure that objects are not duplicated upon deserialization?

Thanks.

© Stack Overflow or respective owner

Related posts about java

Related posts about deserialization