昨天的笔试题, StringBuffer
代码:
1 public static void switchStr(StringBuffer x, StringBuffer y) { 2 x.append(y); 3 System.out.println("(1)" + x); 4 y = x; 5 System.out.println("(2)" + y); 6 } 7 8 public static void main(String args[]) { 9 StringBuffer a = new StringBuffer("A"); 10 StringBuffer b = new StringBuffer("B"); 11 switchStr(a, b); 12 System.out.println("(3)" + a + "," + b); 13 }
执行结果
(1)AB
(2)AB
(3)AB,B
-----------------------------------------------------------------------分割线-----------------------------------------------------------------------
修改一下
1 public static void switchStr(StringBuffer x, StringBuffer y) { 2 x = y; 3 System.out.println("(1) x = " + x); 4 y = x; 5 System.out.println("(2) y = " + y); 6 } 7 8 public static void main(String args[]) { 9 StringBuffer a = new StringBuffer("A"); 10 StringBuffer b = new StringBuffer("B"); 11 switchStr(a, b); 12 System.out.println("(3) a = " + a); 13 System.out.println("(4) b = " + b); 14 }
执行结果
(1) x = B (2) y = B (3) a = A (4) b = B
a 指向 “A”
b 指向 “B”
x = y ,这时候 x 和 y 同时指向 “B”了
y = x ,这句其实没起作用
最终 b x y 同时指向 “B”
a 没变
-----------------------------------------------------------------------分割线-----------------------------------------------------------------------
真的想交换 a b 的话:
1 public static void switchStr(StringBuffer x, StringBuffer y) { 2 StringBuffer temp = x; 3 x = y; 4 System.out.println("(1) x = " + x); 5 y = temp; 6 System.out.println("(2) y = " + y); 7 } 8 9 public static void main(String args[]) { 10 StringBuffer a = new StringBuffer("A"); 11 StringBuffer b = new StringBuffer("B"); 12 switchStr(a, b); 13 System.out.println("(3) a = " + a); 14 System.out.println("(4) b = " + b); 15 }
结果:
(1) x = B
(2) y = A
(3) a = A
(4) b = B