| Author |
String reference remains same during clone()
|
Vijay Raj
Ranch Hand
Joined: Oct 10, 2005
Posts: 110
|
|
In the above code, I have two instance variables, one a primitive type and another a String variable. After calling test(), the integer variable remains the same as expected. But the String reference also remains the same (prints "hello"). Shouldn't the modification made in the method test() be reflected, i.e., it should have printed "again_hello" instead of "hello". This is what shallow copying is, right? regards, vijay.
|
 |
Ko Wey
Ranch Hand
Joined: Sep 08, 2003
Posts: 67
|
|
CloneTest ct1 is declared and initialized within method: test(Object obj) so after leaving this method ct1 (and its string str) do not exist anymore. Isn't this thinking correct?
|
 |
Bimal Patel
Ranch Hand
Joined: Aug 29, 2003
Posts: 130
|
|
Hi, [/qb]<hr></blockquote> Can you try as below: private void test(CloneTest obj) { obj.count = 20; obj.str = new String("again_hello"); } Just a wild guess  [ November 12, 2005: Message edited by: Bimal Patel ]
|
Work Hard, Expect The Worst...<br /> <br />Bimal R. Patel<br />(SCJP 1.2, SCWCD 1.4)
|
 |
Marilyn de Queiroz
Sheriff
Joined: Jul 22, 2000
Posts: 9033
|
|
Vijay R. I am sorry to inform you that a last initial is not the same as a last name. The JavaRanch Name Policy requires a first name, a space, and a last name. You can change it here.
|
JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
|
 |
Vijay Raj
Ranch Hand
Joined: Oct 10, 2005
Posts: 110
|
|
Ko Wey: But we are referencing the same string object, so change made in test() should reflect back. Bimal Patel: Tried making a call to test() from main() as but to no avail. It still prints "hello". regards, vijay.
|
 |
Ko Wey
Ranch Hand
Joined: Sep 08, 2003
Posts: 67
|
|
CloneTest ct = new CloneTest(); ct.test(ct.clone()); out.println(ct.count); out.println(ct.str);
In ct.test(ct.clone()) I make a copy (ct.clone()), I then change the copy (test(ct.clone)) an then I look at the original's members, not those of the copy! If I change the code to this: I get this print-out: ct:10 ct:hello ctx:20 ctx:again_hello which is what was wanted, yes?
|
 |
 |
|
|
subject: String reference remains same during clone()
|
|
|