jeffiepoo
asked on
Deep Copy in Java
Since I've been programming a lot with C and C++, I am a bit confused as to how I'm going to implement something in Java since it manages memory it's own way. Take the following steps for example:
I create a hierarchy of classes, and create an instance of an this object (polymorphism stuff) with specific data values and store it.
Simple enough right?
I will call this my TEMPLATE OBJECT
Now, I want to copy my template object to another object called HELLO, and it needs to be a DEEP COPY because I want to change HELLO in every way, and have the TEMPLATE object unaltered.
How do I do this in Java??
I'm confused because you can't specifically code in a copy constructor or anything like that in Java.
Can I do something like. public example_object temp = new example_object(TEMPLATE) --??
Thanks Experts!!!
I REALLY NEED HELP ON THIS ONE. It's for homework and I gotta get crackin, I'll be sitting by this post. Lets see what ya'll think.
-Jeff
I create a hierarchy of classes, and create an instance of an this object (polymorphism stuff) with specific data values and store it.
Simple enough right?
I will call this my TEMPLATE OBJECT
Now, I want to copy my template object to another object called HELLO, and it needs to be a DEEP COPY because I want to change HELLO in every way, and have the TEMPLATE object unaltered.
How do I do this in Java??
I'm confused because you can't specifically code in a copy constructor or anything like that in Java.
Can I do something like. public example_object temp = new example_object(TEMPLATE) --??
Thanks Experts!!!
I REALLY NEED HELP ON THIS ONE. It's for homework and I gotta get crackin, I'll be sitting by this post. Lets see what ya'll think.
-Jeff
what I have done in the past was to create a deepCopy in each class
my setup was like this
object.deepCopy(oldObject)
this.f1 = oldObject.f1
this.f1 = oldObject.f2
etc
So the first deepCopy you call, it copies the primitive types like ints, strings etc
Now this class had another class (like yours), I would instantiate a new object and call that deepCopy
eg
this.obj1 = new OtherClass()
this.obj1.deepCopy(oldObje ct.getObj1 ())
and so on
my setup was like this
object.deepCopy(oldObject)
this.f1 = oldObject.f1
this.f1 = oldObject.f2
etc
So the first deepCopy you call, it copies the primitive types like ints, strings etc
Now this class had another class (like yours), I would instantiate a new object and call that deepCopy
eg
this.obj1 = new OtherClass()
this.obj1.deepCopy(oldObje
and so on
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
another way is to use serialization
http://javatechniques.com/blog/faster-deep-copies-of-java-objects/