• 昨天的笔试题, 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

  • 相关阅读:
    括号序列
    NOI剑客决斗
    洛谷 P1896 [SCOI2005]互不侵犯King
    codevs贪吃的九头龙
    ie6绝对定位的块会被select元素遮挡的解决方案
    Normalize.css与Reset CSS:定义浏览器统一的默认样式
    IE6中PNG图片背景无法透明显示的最佳解决方案
    关于ie6中绝对定位或浮动的div中既有向左float也有向右float时候如何让外层div自适应宽度的解决方案--
    [Z]关于html中的条件注释
    [z]IE6各种不兼容问题
  • 原文地址:https://www.cnblogs.com/maxiaodoubao/p/4723560.html
Copyright © 2020-2023  润新知