Re: Backing Up Objects
Hal Vaughan wrote:
OK, it's high time *someone* answered the OP's question here.
If you want to do a full deep copy of a data structure, just serialize
and deserialize it. If you want to, to a RAM buffer rather than a
(possibly temporary) disk file. (The TCP/IP loopback interface is
another intriguing possibility.) As an added bonus feature, if you
serialize to a .bak file on disk you get a disk backup that can be
restored later by deserializing it, e.g. after a program abend.
You need to make the stuff you use in this data structure
serializable. The standard collection classes already are
serializable. The Java Tutorial on Sun's Web site has further
information about serialization for beginners.
Now I have some good terms to use for searching. I can work it out from
You will probably find Stefan's advice (the very first answer to your post)
more manageable. Serialization is a topic fraught with perils.
Stefan Ram suggested:
This depends on the circumstances. There are ??shallow?? copies
only copying the fields and ??deep?? copies, where the fields
are altered to refer to copies of subobjects (recursively),
and there are mixtures. Only you can know, what is appropriate
for your requirements. By this knowledge, you can implement
the operation as a method.
Means to copy often are a ??copy constructor?? or the method ??clone??.
You might look up these subjects in the technical literature.
The usual best is to write your own copy method(s).
Serialization requires a number of steps to ensure safety, covered well by
Joshua Bloch's /Effective Java/. You need a serialVersionUID, possibly to
write methods writeObject(), readObject(), readObjectNoData(), writeReplace()
and readResolve(), making certain fields transient, making sure all referenced
objects are also serializable, more threading concerns, possible static
variable trouble, and so on. It creates a back-door constructor and a public
access to the class that must be maintained in perpetuity.
Just writing a copy method is likely to be much easier.