Almost every java developer finds one fine morning that he cannot compare String with “==” as he has been doing with int or char .幾乎每一個Java開發認定,罰款一今天上午表示,他不能比較的字符串與“ == ” ,因為他一直致力與詮釋燒焦 Then either he finds out or someone kindly tells him that objects cannot be compared with “==”.然後,他發現或有人善意地告訴他物體不能與"==". He has to use equals(Object) method.他使用等於(對象)的方法。 However rarely, if ever, he realizes that it is possible to use == to compare two String for equality. There are two great The benefit s of being able to use == for String comparison - improved performance and memory usage reduction.但是很少,如果,他意識到,這是可以使用==比較兩個字符串平等, 有兩個偉大 的利益, S的能夠使用==為字符串比較-更好的性能和記憶體使用量減少。

To achieve this you need to call the magic method - intern() on a String.要達到這個你需要調用魔術方法-實習( )對一個字符串。

String class internally maintains a private pool of strings which are initially empty. String類的內部維持一個私人游泳池的字符串這是最初是空的。

When the intern() method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned.當實習生( )方法是引用,如果泳池中已經包含有一個字串平等這一String對象所確定的等號(對象)方法,然後字符串從池回來了。 Otherwise, this String object is added to the pool and a reference to this String object is returned.否則,這個String對象添加到游泳池和一個參考這個String對象是回來了。

All literal strings and string-valued constant expressions are interned.所有的字面字符串和字符串值不斷表達的是實習。

So if you compare an intern ed String with another intern ed String or String constant then you can safely use == instead of (or in addition to) equals(Object) method.因此,如果您比較一名實習生,教育署字符串與另一實習生教育署字符串或字串常數,然後您可以放心地使用==而不是(或在除) 等於(對象)的方法。

This is widely used while processing large XML documents where the tags are interned for faster comparison and lower memory consumption .這是廣泛使用的同時,處理大型XML文件的地方標記實習更快的比較和較低的內存消耗

Update: Based two comments below by Christian and Markus, I re-evaluated the validity of touted performance benefit. 更新:基於以下兩點意見,由基督教和馬庫斯,我重新評估的有效性,宣揚業績受惠。 With JDK 1.5 (I tested with) there isn’t any performance difference between equals(Object) and == for String.與的JDK 1.5 (我所測試的同)不存在任何性能差異的平等(對象)和==為字符串。 It is most likely because of equals implementation which first does a == comparison anyway as pointed out by這是最有可能的,因為平等的實施,其中第一次做了比較,無論如何==指出 Markus Kohler馬庫斯科勒 . Thanks for correcting me guys.感謝糾正我的朋友。

PS.保安局常任秘書長。 It is amazing how Java is improving over the versions.這是了不起的Java是如何改善以上的版本。 Several previous assumptions of performance are not valid anymore.幾個以前的假設的表現是無效的了。 There goes another.有雲:另一個。 I wonder when String concatenation with + operator will follow suit.我不知道當字串串連與+經營者會仿效。