Re: [問題] 關於StringBuffer與區域變數
※ 引述《pieapple (社會新鮮人)》之銘言:
: Given:
: public class Foo
: {
: 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;
: }
: }
: 小弟執行後的結果是輸出:AB,B
: 但我有些搞亂為什麼b的值是B,而不是AB。
: operate(a,b)之後,a會變成"AB",但b卻還是"B"
: 請各位前輩賜教,謝謝!
希望這樣的例子您能體會啊^^
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
public class Alias {
public static void main(String[] args) throws IOException {
StringBuffer a = new StringBuffer("A");
StringBuffer b = new StringBuffer("B");
// in function, the args is an alias for params
// make alias for b
StringBuffer y = b;
// y's content equals to b's content
System.out.println(y.toString());
// a.append method create a new StringBuffer
// y is assigned to new instance
y=a.append(b);
System.out.println(y.toString());
// now b is not associated with y
System.out.println(b.toString());
System.out.println(a.toString());
}
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 163.26.34.214
討論串 (同標題文章)