zoukankan      html  css  js  c++  java
  • String和StringBuffer 的区别

    一、String是可变类,StringBuffer是不可变类 。

    package test;
    /**
     * Created by Lenovo on 2015/2/9.
     */
    public class Spliter
    {
        public static void main(String[] args) {
          String s=new String("    hello world   " );
            s.toUpperCase();
            s.trim();
            System.out.println(s.toString());
            /*
            输出结果是     hello world   (前后有空格)
            String 创建后它的内容无法改变,toUpperCase,trim等实际是创建并返回一个带有改变后内容的新的字符串对象,toString返回当前的实例本身的引用  *、
             */
    
          StringBuffer sb= new StringBuffer("     hello ");
            sb.append("world     ");
            sb.insert(0, "yoyo");
            System.out.println(sb.toString());
    
             /*
            输出结果是 yoyo   hello world
            StringBuffer 的 insert appender,replaceAll等会改变字符缓冲区中的内容 toString 返回一个当前StringBuffer的缓冲区中内容的新的String对象的引用。
    
             */
        }
    }

    二、String类覆盖了equal方法,StringBufffer没有

     1 package test;
     2 
     3 /**
     4  * Created by Lenovo on 2015/2/9.
     5  */
     6 public class Spliter
     7 {
     8     public static void main(String[] args) {
     9         String s1=new String("hello world" );
    10         String s2=new String("hello world" );
    11         System.out.println(s1==s2);     // 返回false
    12         System.out.println(s1.equals(s2));  // 返回true
    13 
    14         StringBuffer s3=new StringBuffer("hello world" );
    15         StringBuffer s4=new StringBuffer("hello world" );
    16         System.out.println(s1==s2);     // 返回false
    17         System.out.println(s3.equals(s4));  // 返回false
    18     }
    19 }

    三、String对象之间可以用’+‘ 连接 ,StringBuffer不能 。

     1 package test;
     2 
     3 /**
     4  * Created by Lenovo on 2015/2/9.
     5  */
     6 public class Spliter
     7 {
     8     public static void main(String[] args) {
     9         String s1=new String("hello world" );
    10         String s2=new String("hello world" );
    11         String ss=s1+s2;
    12         System.out.println(ss.toString());  //返回 hello worldhello world
    13 
    14         StringBuffer s3=new StringBuffer("hello world" );
    15         StringBuffer s4=new StringBuffer("hello world" );
    16         StringBuffer ss2=s1+s2;  //编译出错
    17         System.out.println(ss2.toString());
    18 
    19 
    20     }
    21 }
  • 相关阅读:
    Pascal's Triangle II
    Pascal's Triangle
    Best Time to Buy and Sell Stock II
    Best Time to Buy and Sell Stock
    Populating Next Right Pointers in Each Node
    path sum II
    Path Sum
    [转载]小波时频图
    [转载]小波时频图
    [转载]Hilbert变换及谱分析
  • 原文地址:https://www.cnblogs.com/assult/p/4281661.html
Copyright © 2011-2022 走看看