Link to home
Start Free TrialLog in
Avatar of jeffiepoo
jeffiepooFlag for United States of America

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
Avatar of Mick Barry
Mick Barry
Flag of Australia image

you need to implement your own copy constructor

another way is to use serialization
http://javatechniques.com/blog/faster-deep-copies-of-java-objects/
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(oldObject.getObj1())

and so on



SOLUTION
Avatar of Valeri
Valeri
Flag of Bulgaria image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial