我期待输出为AB,ABCD,但输出为ABCD,B。这怎么可能?
public class Test {
public static void main(String[] args) {
StringBuffer a = new StringBuffer("A");
StringBuffer b = new StringBuffer("B");
operate(a, b);
System.out.println(a + " " + " , " + " " + b);
}
static void operate(StringBuffer x, StringBuffer y) {
x.append(y);
y = x.append("C");
y.append("D");
}
}
所以最初,你有这个。
a -> [A...] b -> [B...]
然后当你调用operate
时,你会得到两个引用相同的两个StringBuffer
对象的新变量。
a b
-> [A...] -> [B...]
x y
然后你将一个StringBuffer
的内容附加到另一个。
a b
-> [AB...] -> [B...]
x y
然后你将另一个字母附加到第一个StringBuffer
,并重新指向变量y
,使它现在引用与StringBuffer
和a
相同的x
。
a
x -> [ABC...] b -> [B...]
y
你再追加一封信,现在引用第一个StringBuffer
作为y
。
a
x -> [ABCD...] b -> [B...]
y
然后退出operate
并打印出两个StringBuffer
对象的内容。
看起来你认为x.append(y)
返回存储在x
中的新字符串,但事实并非如此。看看here,看到它只返回指向x的指针。
现在有了这种洞察力,再次阅读您的代码并看到您理解输出。