作者qrtt1 (隐者)
看板java
标题Re: [问题] 关於StringBuffer与区域变数
时间Thu Jun 15 09:50:53 2006
※ 引述《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