• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

cloning question

 
Edwin Davidson
Greenhorn
Posts: 27
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
On page 225 of Peter van der Linden's Just Java 2 (5th edition) exercise 5 is written as this:

"write some code to clone an object of your class. Change your version of
clone() to do a deep copy for your class. Run the clone program again,
and make it print out enough details that you can tell the difference
between a shallow and a deep clone."

The exercise before it (exercise 4) says to override Object.clone() to do
a shallow copy for your class. My code for exercise 4 is here:
============================================================================
class testclass implements Cloneable {

public Object clone() throws CloneNotSupportedException {
System.out.println("clone "+ ++count);
return super.clone();
}

int geti() {
return i;
}

int i;
double d;
static int count;

testclass() {
i=4;d=5.5;
System.out.println("constructor "+ ++count);
}
}


class exercise4 {
public static void main(String args[]) throws
CloneNotSupportedException {
testclass tc1=new testclass();
testclass tc2;
tc2=(testclass) tc1.clone();
System.out.println("tc1 d "+tc1.d);
System.out.println("tc1 i "+tc1.i);
System.out.println("clone d "+tc2.d);
System.out.println("running clone geti() "+tc2.geti());
}
}
============================================================================
How do I do a deep clone ? The code can't be that much different. I know
if I see the code for it I'll know how it works straight off.

Thanks to all.
Edwin
 
Nigel Browne
Ranch Hand
Pie
Posts: 682
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This whitepaper will help you understand the difference between shallow and deep cloning.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In a nutshell, cloning provides only a shallow copy because the member references still point to the same objects as in the original copy. For a deep copy, you would need to also clone any member objects as well (and any member objects of those objects, and so on...).

See Appendix A to Bruce Eckel's Thinking in Java...

http://www.faqs.org/docs/think_java/TIJ319.htm
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic