【发布时间】:2021-09-20 06:24:12
【问题描述】:
我很困惑为什么在第一个代码(代码 1)中,myCounter 指向的对象在传递给方法“print”后被更新为值 2。 但是在第二个代码(代码 2)中,str 指向的对象仍然是同一个字面量“This is a string literal”。我认为 str(str 是一个对象引用,就像我认为的 myCounter 一样)经历相同的机制,因为它也被传递给一个方法,所以它不应该像 myCounter 一样更新吗?
这是代码 1:
public class PrimitiveVsReference{
private static class Counter {
private int count;
public void advance(int number) {
count += number;
}
public int getCount() {
return count;
}
}
public static void main(String args[]) {
int i = 30;
System.out.println("value of i before passing to method : " + i);
print(30);
System.out.println("value of i after passing to method : " + i);
Counter myCounter = new Counter();
System.out.println("counter before passing to method : " + myCounter.getCount());// this gives 0
print(myCounter);
System.out.println("counter after passing to method : " + myCounter.getCount());// now this gives 2 after passing into the method "print"
}
/*
* print given reference variable's value
*/
public static void print(Counter ctr) {
ctr.advance(2);
}
/**
* print given primitive value
*/
public static void print(int value) {
value++;
}
}
代码 2:
String str = "This is a string literal.";
public static void tryString(String s)
{
s = "a different string";
}
tryString(str); // isn't this here doing the samething as when myCounter is passed to print in Code 1?
System.out.println("str = " + str); // But this here output the original literal "This is a string literal."
有人可以解释发生了什么吗?
【问题讨论】:
-
这是修改对象内容(代码1)和创建新对象(代码2)的区别。
-
@MarkRotteveel 所以根据你所说的,user16320675 的第二个答案(没有得到任何投票的解释)是正确的推理。第一个答案(有 2 个赞成票的那个)给出的推理不是正确的答案(即它与不可变或可变无关,对吧?)。这是正确的吗?因为我想了解正确的解决方案。
-
是的,没错。事实字符串是不可变的与此无关(如果您在代码 1 中的
print中使用了ctr = new Counter(),并且Counter是一个可变对象,也会发生同样的情况)。 -
@MarkRotteveel 哦,感谢您指出正确的解决方案。
标签: java