3

I want to find an efficient way to clone a big system object (planetary system in my case) with all its sub-objects. The sub-objects have coordinates and stuff like that, planets etc. So a deep copy, i guess..

I tried cloning and some serializable hacks, didn't seem to be working, the copy's sub-objects attributes didn't remain constant as I tried printing the copy's certain planets coordinates after i made the copy and the planets continued orbitting.

My main goal is to save a current state of the whole systems object positions, states etc. and recover back to it at any given time after the copy has been made. Hope I haven't misunderstood anything..

  • 5
    This answer has some helpful solutions: http://stackoverflow.com/questions/2156120/java-recommended-solution-for-deep-cloning-copying-an-instance – cklab May 31 '12 at 19:28
  • http://stackoverflow.com/questions/64036/how-do-you-make-a-deep-copy-of-an-object-in-java – MK. May 31 '12 at 19:32

2 Answers2

1

If you must persist your objects and restore state at the later time you should use java serialization or for example db4o (this is really easy to use).

Serialization should work also - every class you aggregate in your "universe" (and "universe" itself) should implement Serializable interface, and any field you don't want to serialize should be marked as transient.

Xeon
  • 5,949
  • 5
  • 31
  • 52
1

One approach I have used is to use the xstream package from Codehaus (http://x-stream.github.io/) to serialize/deserialize directly. Something like:

XStream xs = new XStream();
MyObjectTree to;

 ///from is an instance of MyObjectTree
to = (MyObjectTree)xs.fromXML(xs.toXML(from));
MonkeyPushButton
  • 1,077
  • 10
  • 19
Jere
  • 581
  • 2
  • 3