深入淺出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"。
閱讀全文