Java常用資訊

來源:互聯網
上載者:User

標籤:stringbuilder   stringbuffer   

一、Equals和==運算子

代碼:

public static void test() {     String x = "hello";      String y = "world";      String z = new String("helloworld");     String a = "helloworld";     System.out.println("x+y equals z:" + (x + y).equals(z));     System.out.println("a == z:" + (a == z));     System.out.println("x == hello:" + (x == "hello"));     System.out.println("a == helloworld:" + (a == "hello" + "world"));     System.out.println("a == x+y:" + (a == (x + y)));  }

 結果:

    x+y equals z:true

    a == z:false

    x == hello:true

    a == helloworld:true

    a == x+y:false

     

    分析:

    1.String.equals()方法比較的是字串的內容,所以(x + y).equals(z)為true.

    2.“==”比較的是 String 執行個體的引用,很明顯 a 和z 並不是同一個 String 執行個體,所以(a == z)為false.

    3.根據常量池的知識,容易得知(x == "hello")和(a == "hello" + "world")都為true.

    (常量池指的是在編譯期被確定並被儲存在已編譯的.class 檔案中的一些資料。它包含了

    關於方法、類、介面等,當然還有字串常量的資訊。也就是所謂的持久代。)

    4.那麼(a == (x + y))為什麼是false呢?這點暫點有點不大清楚。初步認為是x+y是引用相加,不能放入常量池。

二、String、StringBuffer、StringBuilder的區別

1.可變與不可變

  String類中使用字元數組儲存字串,如下就是,因為有“final”修飾符,所以可以知道string對象是不可變的。

    private final char value[];

  StringBuilder與StringBuffer都繼承自AbstractStringBuilder類,在AbstractStringBuilder中也是使用字元數組儲存字串,如下就是,可知這兩種對象都是可變的。

    char[] value;

2.是否多安全執行緒

  String中的對象是不可變的,也就可以理解為常量,顯然安全執行緒。

  AbstractStringBuilder是StringBuilder與StringBuffer的公用父類,定義了一些字串的基本操作,如expandCapacity、append、insert、indexOf等公用方法。

  StringBuffer對方法加了同步鎖或者對調用的方法加了同步鎖,所以是安全執行緒的。

      StringBuilder並沒有對方法進行加同步鎖,所以是非安全執行緒的。

3.StringBuilder與StringBuffer共同點

  StringBuilder與StringBuffer有公用父類AbstractStringBuilder(抽象類別)。

  抽象類別與介面的其中一個區別是:抽象類別中可以定義一些子類的公用方法,子類只需要增加新的功能,不需要重複寫已經存在的方法;而介面中只是對方法的申明和常量的定義。

  StringBuilder、StringBuffer的方法都會調用AbstractStringBuilder中的公用方法,如super.append(...)。只是StringBuffer會在方法上加synchronized關鍵字,進行同步。

      對於三者使用的總結:

            1.如果要操作少量的資料用 = String
            2.單線程操作字串緩衝區 下操作大量資料 = StringBuilder
    3.多線程操作字串緩衝區 下操作大量資料 = StringBuffer





本文出自 “ciyo技術分享” 部落格,請務必保留此出處http://ciyorecord.blog.51cto.com/6010867/1928573

Java常用資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.