• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

String reference remains same during clone()

 
Vijay Raj
Ranch Hand
Posts: 110
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 67
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 130
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Marilyn de Queiroz
Sheriff
Posts: 9059
12
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Vijay Raj
Ranch Hand
Posts: 110
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 67
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic