How could you reform a shallow copy to a deep copy? For example, the field creator is the "Name" of the class type, the reference of the creator is c1 is copyied into c2. Thus c1.getCreator() == c2.getCreator() . Any advice? Thanks, Ryan Vines
Perhaps your question would be clearer if you were to post some more relevant example code. Concerning the concept of a shallow copy versus a deep copy: Consider the following (contrived) example. The big difference between a shallow copy and a deep copy is that in the shallow copy, instance members are reused in the copy. In a deep copy, copies of instance members are used to create the copy. Note that in the above example, any instance members of bar should also be deep-copied during the deep copy.
Well, my question i am asking is how i could change a shallow copy to a deep copy. Like the exapmle i gave above creats shallow copies, not deep. I was wondering how you could change it to make the shallow copies deep copies.
To perform a deep copy, one would normally implement the Object.clone() method, implementing Cloneable .... much as in C++ with the copy constructor. Inside the clone() method, we would call clone on all the instance variables, resulting in a separate but identical object, with no instance sharing between the two objects. If, however, some of your instance variables don't implement Cloneable, you would have to manually clone them by using the objects exposed interfaces. Maybe that would help you a bit. I didn't go through the code you posted. Much too long and way too lazy.
Originally posted by ryan vines: ok, well how would that to apply if you had subclasses and methods to deal with. Take this code for example [...]
You would need to rework the clone() method like this:
Note that I removed the try..catch block so that CloneNotSupportedException will propagate to the caller. My take is that it's better to fail than return a null from the clone() method as it's expected that a real object will be returned.
Joined: Dec 08, 2003
Ok, Thanks alot guys, i fully understand how deep coping works now. and all that is thanks to you giving me help. Sincerely, Ryan Vines