Using method clone for an Object
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Hari_Rajagopalan
Posted On:   Wednesday, October 16, 2002 10:34 AM

I have this doubt in Java, thought I would check it out with you. Hope its allright. I have a class called schedule This is rough structure of my code. Schedule S1 = new Schedule(); S1 = S1.getvalues(S1); Schedule Solution = S1.clone(); S1=S1.changevalues(S1); // I have changed the values here S1.display(); solutoin.display(); Now I assumed that since Solution was a clone of S1 its values wont change since it creates a copy with a separate memory location but if I print the values from Solution and S1 they are both the same What am I doing wrong? To go into a little more detail about the Class Schedule It contains a String S ; Vector V and a Vector A which contains a set Objects   More>>

I have this doubt in Java, thought I would check it out with you. Hope its allright. I have a class called schedule This is rough structure of my code.

Schedule S1 = new Schedule();
S1 = S1.getvalues(S1);
Schedule Solution = S1.clone();
S1=S1.changevalues(S1); // I have changed the values here
S1.display();
solutoin.display();

Now I assumed that since Solution was a clone of S1 its values wont change since it creates a copy with a separate memory location but if I print the values from Solution and S1 they are both the same What am I doing wrong?

To go into a little more detail about the Class Schedule
It contains a String S ; Vector V and a Vector A which contains a set Objects Unit from Class Unit Unit contains an attribute Vector Z;

Now in this example String s does not change there is no problem.
However Vector V for solution and s1 have the same value even after i change the values for it
I found a way out by entering
Solution.V = (Vector)S1.V.clone(); after Schedule Solution = S1.clone();
However I have not been able to get this done with Vector A even if do a loop and clone each of the Vector Zs.
Hari

   <<Less

Re: Using method clone for an Object

Posted By:   Christopher_Koenigsberg  
Posted On:   Wednesday, October 16, 2002 10:53 AM

The result of a "clone" method can be fully "deep", or just 1-layer "shallow", or somewhere in between, so it depends on exactly how it is implemented, in the classes you are using -- not just the "clone" method in the top level object, but also the "clone" methods in all the member fields, and their own member fields, etc. all the way down.



Because of this, and issues with subclasses overriding "clone" vs. declaring a final version, and possibly not implementing it fully or even throwing "CloneNotSupported", most authors (e.g. Josh Bloch's "Effective Java", Bruce Eckel's "Thinking in Java", the "Java Practices" Web site) warn that you shouldn't depend on "clone" doing what you need, necessarily, if you don't have control over the code for all the objects involved.

About | Sitemap | Contact