Java字串池

來源:互聯網
上載者:User

標籤:main   string   text   []   intern方法   等於   als   模型   har   

1. String的兩個建構函式
private final char value[];private int hash;public String() {    this.value = "".value;}
public String(String original) { this.value = original.value; this.hash = original.hash;}
2. new String中建立幾個String對象?1)建立兩個String對象
public static void main(String[] args) {    String y = new String("hello");}

記憶體模型如下:

2)建立一個String對象
public static void main(String[] args) {    String x = "hello";    String y = new String("hello");}

記憶體模型如下:

3. String的intern方法

String類私人地維護著一個初始為空白的字串池,當調用intern方法時:

1. 若字串池中已包含一個等於此String對象的字串(用 equals方法確定),則返回池中的字串。
2. 否則,將此String對象添加到池中,並返回此String對象的引用。

public native String intern();

字串池中存放的是String對象引用,而不是String對象本身。

實驗:

public static void main(String[] args) {    String x = "hel";    x += "lo";    String y = "ja";    y += "va";    System.out.println(x == x.intern()); // true    System.out.println(y == y.intern()); // false}

y == y.intern()為false說明字串池中已存在"java",JVM啟動時在字串池中載入的字串還包括:"true"、"false"...

記憶體模型:

intern前

intern後

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.