為什麼兩個打印結果不一樣
public static void main(String[] args) {
StringBuffer a = new StringBuffer("A");
StringBuffer b = new StringBuffer("B");
operator(a,b);
System.out.println("main方法:" + a + "," + b);
}
private static void operator(StringBuffer a, StringBuffer b) {
a.append(b);
b = a;
b.append(a);
System.out.println("operator:" + a + "," + b);
}
結果如下
operator:ABAB,ABAB
main方法:ABAB,B
你在operator方法中,當b=a時,b所對應的內存,已經不是原來new 出來的內存,而是和a指向了同一塊內存,所以在後面的b.append(a)中,a才會輸出ABAB;而b的內存和a是同一塊,所以b也是ABAB。
而在main中,a所在內存的值已經變為ABAB了,但是b的內存由於在operator的b.append之前,所指的內存已經改變,所以還是B
要是一樣的話,可以按我下面寫的
public class Test {
static StringBuffer a=null;
static StringBuffer b=null;
public static void main(String[] args) {
a= new StringBuffer("A");
b = new StringBuffer("B");
Test t=new Test();
t.operator(a,b);
System.out.println("main方法:" + a + "," + b);
}
private void operator(StringBuffer c, StringBuffer d) {
a=c;
b=d;
a.append(b);
b = a;
b.append(a);
System.out.println("operator:" + a + "," + b);
}
}