理解String.intern()

  • java.lang.String
/**
     * Returns a canonical representation for the string object.
     * <p>
     * A pool of strings, initially empty, is maintained privately by the
     * class {@code String}.
     * <p>
     * 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.
     * <p>
     * It follows that for any two strings {@code s} and {@code t},
     * {@code s.intern() == t.intern()} is {@code true}
     * if and only if {@code s.equals(t)} is {@code true}.
     * <p>
     * All literal strings and string-valued constant expressions are
     * interned. String literals are defined in section 3.10.5 of the
     * <cite>The Java&trade; Language Specification</cite>.
     *
     * @return  a string that has the same contents as this string, but is
     *          guaranteed to be from a pool of unique strings.
     */
    public native String intern();

  • intern方法用來(lái)返回常量池中的某字符串,如果常量池中已經(jīng)存在該字符串,則直接返回常量池中該對(duì)象的引用较沪。否則,則常量池中加入該對(duì)象失仁,然后返回引用尸曼。

String設(shè)計(jì)成不可變的原因

  • 字符串常量池的需要。字符串常量池的誕生可以提高效率萄焦,減少內(nèi)存分配控轿。String的不可變,常量池可以很容易的被管理和優(yōu)化拂封。
  • 安全性考慮茬射。字符串使用的場(chǎng)景很多,設(shè)計(jì)成不可變的可以有效的防止字符串被有意或無(wú)意的被篡改冒签。
  • 作為HashMap在抛、HashTable等hash類型key的必要。因?yàn)镾tring被設(shè)計(jì)成不可變的萧恕,JVM底層很容易在緩存String對(duì)象的時(shí)候緩存其hsahCode刚梭,這樣在執(zhí)行效率上會(huì)大大提升肠阱。

創(chuàng)建字符串

  • 直接使用雙引號(hào)創(chuàng)建字符串
    • 判斷這個(gè)常量是否存在于常量池
      • 如果存在,判斷這個(gè)常量是存在的引用還是常量
        • 如果是引用朴读,則返回引用地址指向的堆空間對(duì)象
        • 如果是常量屹徘,則直接返回常量池常量
      • 如果不存在
        • 在常量池中先創(chuàng)建該常量,并返回此常量
        String s1 = "hello";  // 在常量池中創(chuàng)建常量
        String s2 = "hello";  // 直接返回已經(jīng)存在的常量
        String s1 = "hello";
        String s2 = "hello";
        System.out.println(s1 == s2);        // true
        System.out.println(s1.equals(s2));    // true
        String s1 = new String("hello");  // 在堆上創(chuàng)建字符串對(duì)象
        s1.intern();    // 在常量池中創(chuàng)建對(duì)象的引用
        String s2 = "hello";  // 常量池中存在該常量衅金,直接返回該引用指向的堆空間對(duì)象
        String s1 = new String("hello").intern();
        String s2 = "hello";
        System.out.println(s1 == s2);      // true
        System.out.println(s1.equals(s2));      // true
  • new String();
    • 首先在堆上創(chuàng)建對(duì)象
    • 然后判斷常量池上是否存在字符串的字面量
      • 如果不存在噪伊,在常量池中創(chuàng)建常量
      • 如果存在,不做任何操作
        String s1 = new String("hello");
        String s2 = new String("hello");
        System.out.println(s1 == s2);      // false
        System.out.println(s1.equals(s2));    // true
        String s1 = new String("hello").intern();
        String s2 = new String("hello").intern();
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));    // true
        String s1 = new String("hello").intern();
        String s2 = "hello";
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));  // true
  • String.valueOf();
    /**
     * Returns the string representation of the {@code Object} argument.
     *
     * @param   obj   an {@code Object}.
     * @return  if the argument is {@code null}, then a string equal to
     *          {@code "null"}; otherwise, the value of
     *          {@code obj.toString()} is returned.
     * @see     java.lang.Object#toString()
     */
    public static String valueOf(Object obj) {
        return (obj == null) ? "null" : obj.toString();
    }
        String s1 = String.valueOf("hello");
        String s2 = "hello";
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));    // true
        String s1 = String.valueOf("hello");
        String s2 = String.valueOf("hello");
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));    // true
        String s1 = String.valueOf("hello");
        String s2 = new String("hello").intern();
        System.out.println(s1 == s2);    // true
        System.out.println(s1.equals(s2));    // truee
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末氮唯,一起剝皮案震驚了整個(gè)濱河市鉴吹,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌您觉,老刑警劉巖拙寡,帶你破解...
    沈念sama閱讀 217,406評(píng)論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異琳水,居然都是意外死亡肆糕,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評(píng)論 3 393
  • 文/潘曉璐 我一進(jìn)店門在孝,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)诚啃,“玉大人,你說(shuō)我怎么就攤上這事私沮∈际辏” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,711評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵仔燕,是天一觀的道長(zhǎng)造垛。 經(jīng)常有香客問(wèn)我,道長(zhǎng)晰搀,這世上最難降的妖魔是什么五辽? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,380評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮外恕,結(jié)果婚禮上杆逗,老公的妹妹穿的比我還像新娘。我一直安慰自己鳞疲,他們只是感情好罪郊,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,432評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著尚洽,像睡著了一般悔橄。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,301評(píng)論 1 301
  • 那天橄维,我揣著相機(jī)與錄音尺铣,去河邊找鬼。 笑死争舞,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的澈灼。 我是一名探鬼主播竞川,決...
    沈念sama閱讀 40,145評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼叁熔!你這毒婦竟也來(lái)了委乌?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 39,008評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤荣回,失蹤者是張志新(化名)和其女友劉穎遭贸,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體心软,經(jīng)...
    沈念sama閱讀 45,443評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡壕吹,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,649評(píng)論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了删铃。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片耳贬。...
    茶點(diǎn)故事閱讀 39,795評(píng)論 1 347
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖猎唁,靈堂內(nèi)的尸體忽然破棺而出咒劲,到底是詐尸還是另有隱情,我是刑警寧澤诫隅,帶...
    沈念sama閱讀 35,501評(píng)論 5 345
  • 正文 年R本政府宣布腐魂,位于F島的核電站,受9級(jí)特大地震影響逐纬,放射性物質(zhì)發(fā)生泄漏蛔屹。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,119評(píng)論 3 328
  • 文/蒙蒙 一风题、第九天 我趴在偏房一處隱蔽的房頂上張望判导。 院中可真熱鬧,春花似錦沛硅、人聲如沸眼刃。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,731評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)擂红。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間昵骤,已是汗流浹背树碱。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,865評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留变秦,地道東北人成榜。 一個(gè)月前我還...
    沈念sama閱讀 47,899評(píng)論 2 370
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像蹦玫,于是被迫代替她去往敵國(guó)和親赎婚。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,724評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容

  • 前言 RTFSC (Read the fucking source code )才是生活中最重要的樱溉。我們天天就是要...
    二毛_coder閱讀 455評(píng)論 1 1
  • 從網(wǎng)上復(fù)制的挣输,看別人的比較全面,自己搬過(guò)來(lái)福贞,方便以后查找撩嚼。原鏈接:https://www.cnblogs.com/...
    lxtyp閱讀 1,345評(píng)論 0 9
  • 注:都是在百度搜索整理的答案,如有侵權(quán)和錯(cuò)誤挖帘,希告知更改完丽。 一、哪些情況下的對(duì)象會(huì)被垃圾回收機(jī)制處理掉 ?當(dāng)對(duì)象對(duì)...
    Jenchar閱讀 3,224評(píng)論 3 2
  • ??需要說(shuō)明的一點(diǎn)是肠套,這篇文章是以《深入理解Java虛擬機(jī)》第二版這本書(shū)為基礎(chǔ)的舰涌,這里假設(shè)大家已經(jīng)了解了JVM的運(yùn)...
    Geeks_Liu閱讀 14,015評(píng)論 5 44
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒(méi)有地址/指針的概念1.2> 泛型1.3> 類型嚴(yán)謹(jǐn) 對(duì)...
    cosWriter閱讀 11,100評(píng)論 1 32