深入淺出Java String(中)__Java

來源:互聯網
上載者:User
深入淺出Java String(中)

閱讀原文 1. 序言

在上篇中,介紹了Java中String對象的組成元素,2種建立的不同之處以及在記憶體地區的不同表現。上次遺留了一個問題,就是String在不同的JDK版本,intern方法有何不同呢。本篇就主要討論下intern()方法帶來的問題。 2. intern方法 2.1. API介紹

首先看下官方的API說明:

When the intern method is invoked, if the pool already contains a string equal to this {@code String} object as determined by the {@link #equals(Object)} method, then the string from the pool is returned. Otherwise, this {@code String} object is added to the pool and a reference to this {@code String} object is returned.

翻譯成中文的意思就是說,當調用intern方法時,如果String常量池中存在這個對象,則返回常量池中的;如果沒有,先加入常量池,在返回。 2.2. JDK版本問題

下面來看一段代碼:

// 代碼1:String str1 = new String("hello"); //建立幾個對象。答案2個String str2 = str1.intern();System.out.println(str1 == str2); //JDK1.6:false,JDK1.7:false// 代碼2:String str3 = new StringBuilder("he").append("llo").toString(); //此時又建立幾個對象。答案1個,不算"he"和"llo"String str4 = str3.intern();System.out.println(str3 == str4); //JDK1.6:false,JDK1.7:true

接下來我們分析一下這個結果的差異:
代碼1: str1是new出來的,即str1指向堆記憶體,而str2是調用str1的intern()方法,即str2是指向常量池的,所以結果在JDK1.6、1.7中都是str1 != str2。要注意的是,此時在建立str1之後,因為new的時候是以"hello"作為初始值的,所以常量池中也會建立一個"hello",所以當調用intern時是直接返回的常量池的引用。
代碼2: str3是通過StringBuilder#toString()建立的,StringBuilder內部的實現過程就是把自身的value作為String對象的value,然後調用Arrays.copyOfRange複製,所以此時常量池中還沒有"hello"。

閱讀全文

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.