I have a node tree built out of Node objects. They are more complex than the code I am showing but only have primitive or Serializable instance members.
Assuming each Node can have up to 10 children the code looks a bit like so.
public class Node implements Serializable{ private static final long serialVersionUID = -848926218090221003L; private Node _parent; private boolean _hasParent; private Node[] _children; private int _childCount = 0; public Node(Node parent){ _children = new Node[10]; _parent = parent; _hasParent = (parent != null); } ... //Various accessors etc }
Now this tree is quite expensive to build but once it is done I write it to a file:
ObjectOutputStream serializedOuput = new ObjectOutputStream(new FileOutputStream(cacheFile)); serializedOuput.writeObject(tree); serializedOuput.close();
When I am done caching the tree I make some irreversable changes to like trimming off unneeded branches.
Then when I next need a base tree to work from I create a new tree object by reading in my serialized file.
The problem…
Creating the tree from the file seems to simply create a new object that points to the old one. In other words the modifications made after writing to file have also been made to the new tree.
If I restart the app and try reading in the serialized file it returns null.
So I seem to be serializing object references rather than the object itself, any ideas where I am going wrong?
Works for me, GNU/Linux with gij 4.3.2.
Make sure all of your fields in the Node class are serializable as well.
This is the code I tried (should be equivalent to yours):