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

  • 相关阅读:
    EasyExcel无法用转换器或者注解将java字段写入为excel的数值格式
    IE浏览器报400错误:Invalid character found in the request target. The valid characters are defined in RFC 7230 and RFC 3986
    list集合根据字段分组统计转换成map
    博客调网易云歌单JS
    如何一次性add library to classpath
    有趣的统计数据表格显示
    span标签的巧用
    "错误: 找不到或无法加载主类"解决办法
    通过改变注入方式以消除警告
    day17--作业
  • 原文地址:https://www.cnblogs.com/maxiaodoubao/p/4723560.html
Copyright © 2020-2023  润新知