How To Compare Strings With == in Java如何比較字符串==在Java
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.我不知道當字串串連與+經營者會仿效。
Filed under提起下 Headline News頭條新聞 , , How To如何 , , Java Software Java軟件 , , Tech Note技術說明 | |
| |
RSS 2.0 2.0 | |
Email this Article電子郵件此文章
You may also like to read您也可以想讀 |




February 26th, 2006 at 3:52 am 2006年2月26日在上午03時52分
This is highly problematic.這是高度問題。 intern() will pollute the intern constant pool and you will not get the entries out of the pool.實習( )會污染實習生常數池和您將無法獲得參賽作品走出泳池。 I think it is the best to use a private data structure mimicking the behaviour.我認為這是最好地利用私人數據結構模仿的行為。
February 26th, 2006 at 8:13 am 2006年2月26日在上午8時13分
Hi,嗨,
I’m not sure whether using intern should really be recommended.我不知道是否使用實習生真的要被推薦。
Actually if you compare the speed of intern versus a simple hashmap at least on SUN JDK 1.4 the hashmap is much faster.其實如果您比較的速度實習生銀兩一個簡單的hashmap至少在Sun的JDK 1.4 hashmap快得多。 Another point is the String.equals first compares for == anyway.另一點是string.equals第一比較為==無論如何。 So there’s almost no point to use == directly.因此,幾乎沒有一點使用==直接。
You are right some XML parsers use intern, but I’m not sure that is optimal.你說得對一些XML解析器使用實習生,但我不能肯定這是最優。 They may save some memory by using intern instead of a simple HashMap.他們可以節省一些內存使用實習生而不是一個簡單的hashmap 。
Regards,關心,
Markus馬庫斯
February 26th, 2006 at 9:00 am 2006年2月26日上午9:00
Thanks for the correction.感謝更正。 I checked with sample code and you guys are absolutely right.我查了與示例代碼和你們是絕對正確的。 With current versions of JDK (I tested with 1.5) I couldn’t find any performance difference.與當前版本的JDK (我所測試的150 )我無法找到任何的性能差異。
However I couldn’t understand the “intern() will pollute the intern constant pool and you will not get the entries out of the pool” part.不過,我無法理解的“實習( )會污染實習生常數池和您將無法獲得參賽作品走出泳池”的一部分。
Do you mean not being able to garbage collect?你的意思未能垃圾收集?
Christian, can you please clarify?基督教,可以請你澄清?
February 27th, 2006 at 2:29 am 2006年2月27日在上午02時29分
Older JVMs will put .intern()’ed strings into a pool of strings that live for the duration of the JVM instance.老年人jvms將付諸表決。實習生( ) '教育署字符串成為一個游泳池字符串活的期限以及JVM的實例。 Thus, if a long-living process uses .intern() on dynamic strings, it will eventually run out of memory.因此,如果一項長期的生活過程中的用途。實習生( )的動態弦樂團,它最終將一發不可收拾的記憶體。
A quick test is this program:快速測試是這一計劃:
public static void main(String[] args) {公共靜態無效的主要(字符串[ ] args ) (while (true) {而(真實) (System.out.println(String.valueOf(Math.random()).intern());system.out.println ( string.valueof ( math.random ( ) ) 。實習( ) ) ;})})- it may run out of memory. -它可能失控的記憶。
March 1st, 2006 at 2:14 am 2006年3月1日在上午02時14分
Hi,嗨,
Regarding your last comment, it was my understanding that since 1.5 there are no performance advantages to doing:關於你的最後評論,這是我的理解是,自5月1日有沒有性能優勢做:
StringBuffer buff = New StringBuffer(”first bit”);stringbuffer迷=新stringbuffer ( “首位” ) ;buff.append(” next bit”);buff.append ( “明年位”) ;instead of:而不是:
String myString = “first bit”+”next bit”;字符串mystring = “第一位” + “明年位” ;as most 1.5 jvm implement the string + operator using the StringBuffer class anyway.由於大部分1.5的JVM執行字符串+經營者使用stringbuffer階級無論如何。
Please correct me if I am wrong.請糾正我,如果我是錯的。
March 23rd, 2006 at 11:35 am 2006年3月23日在上午11時35分
In your specific case,在您的特定情況下,
String myString = "first bit"+"next bit";字符串mystring = “第一位” + “明年位” ;is still better, since the compiler will do the仍然是更好的,因為編譯器也將這樣做
optimization while compiling - so it will compile to the same bytecode as優化的同時,編制-因此,將編譯為相同的字節作為
String myString = "first bitnext bit";字符串mystring = “第一bitnext位” ;But for the more general case where it is not constant strings, you are almost right.但對於較一般的情況下,這不是常數弦樂團,你是差不多的權利。
The only difference is that in java 1.5 the compiler will use a StringBuilder - it’s just like StringBuffer, but without the synchronisation.唯一的區別是在Java 1.5編譯器將使用StringBuilder的-這就像s tringbuffer,但沒有同步。 With some JVM’s, this might make the + version marginally faster.與一些的JVM的,這可能使+版本有輕微的速度更快。
As well as more readable.以及更具可讀性。
Now, if you start doing multiple concatenations in different statements, it is a different matter.現在,如果你開始做多串連在不同的報表,這是一個不同的問題。 In that case, using an explicit StringBuilder will save the jvm from constructing a lot of temporary StringBuilders.在這種情況下,使用一個明確的StringBuilder將保存的JVM ,從建設了很多臨時stringbuilders 。
It will be much faster to do它將快得多做
StringBuilder result = new StringBuilder();StringBuilder的結果=新的StringBuilder ( ) ;for(int i = 0; i(詮釋= 0 ;我than比
String result = “”;字符串的結果= “ ” ;for(int i = 0; i(詮釋= 0 ;我March 23rd, 2006 at 11:37 am 2006年3月23日在上午11時37分
Whoops - the parser ate my <’s.哎呀-分析器吃了我的< “第
Anyway, you get my menaing.無論如何,你讓我menaing 。
March 23rd, 2006 at 11:44 am 2006年3月23日在上午11時44分
Yes是
April 2nd, 2006 at 5:25 am 2006年4月2日在上午05時25分
Hi嗨
I am in urgent need for the program in java which compares two huge strings and return boolean value我在迫切需要的程序在Java相比,兩個龐大的弦樂團及返回布爾值
Do help me by giving the appraoch and code這樣做能幫助我給予appraoch和代碼
with regards對於
seenu
April 3rd, 2006 at 3:38 am 2006年4月3日在上午03時38分
String.equals() string.equals ( )
December 24th, 2006 at 12:09 pm 2006年12月24日在下午12時09分
out.println(” user from form”);String name3= request.getParameter(”uname”);out.println(name3); out.println ( “用戶從形式” ) ;字符串name3 = request.getparameter ( “ uname ” ) ; out.println ( name3 ) ;
out.println(”user from DB”);String name1= rs.getString(”uname”);out.println(name1); out.println ( “用戶從分貝” ) ;字符串name1 = rs.getstring ( “ uname ” ) ; out.println ( name1 ) ;
String test=name1;字符串測試= name1 ;
out.println(”pass from DB”);String name2= rs.getString(”pass”);out.println(name2); out.println ( “通過從分貝” ) ;字符串name2 = rs.getstring ( “通行證” ) ; out.println ( name2 ) ;
out.println(” pass from form”);String name4= request.getParameter(”pass”);out.println(name4); out.println ( “通過從形式” ) ;字符串name4 = request.getparameter ( “通行證” ) ; out.println ( name4 ) ;
if (name3.equals(name1))如果( name3.equals ( name1 ) )
{ (
out.println(”Authentication successful- usewwerwrwrname is correct”); out.println ( “驗證成功- usewwerwrwrname是正確的” ) ;
} )
else {否則(
out.println(”kindly check your usernasame and/or password”); out.println ( “善意檢查您的usernasame和/或密碼” ) ;
} )
the above are my codes, i get the output in the jsp page as :以上是我的守則,我得到的輸出,在JSP的網頁為:
user from form krishna用戶從形式和Krishna
user from DB krishna用戶從分貝克利須那
pass from DB krishna通過從分貝克利須那
pass from form krishna通過從形式和Krishna
kindly check your usernasame and/or password好心檢查您的usernasame和/或密碼
what is wrong in my statement… the strings are same, but the if clause is not executed..什麼是錯在我的發言…字符串相同的,但是如果第,是不會被執行.. will be kindful to know the answer..將kindful知道答案..
January 26th, 2007 at 10:33 am 2007年1月26日在上午10時33分
Krishna: you may want to make sure there’s no trailing spaces by doing:克里希納:你可能希望把,相信總有沒有尾隨空格這樣做:
if (name3.trim().equals(name1.trim()))…如果( name3.trim ( ) 。等於( name1.trim ( ) ) ) … …
Or even compare case-insensitively by using或什至比較案例insensitively使用
name.toUpper(); // I think name.toupper ( ) ; / /我覺得
At least if you want to be Microsoftish至少如果你想成為microsoftish
otherwise I see not problems with your code… (other than calling passwords for “name” — be careful with variable names or it will come back and bite you some day… had a colleague that used zib and zob and variations thereof for his variable names… guess how fun that was to work with? ;o)否則,我見沒有問題,與您的代碼… … (以外的其他要求密碼“名稱” -小心變數名稱或它會回來和咬你有一天…有一個同事用的z ib和z ob和變異為他的變數名稱…猜如何好玩,這是一起工作? ;海外)
HTH hth
/Erik /埃里克
March 1st, 2008 at 8:38 am 2008年3月1日在上午8時38分
how to uncompare 2 strings??如何uncompare 2字符串嗎?
if (arr3[u].equalsIgnoreCase(search))如果( arr3 [ u ] 。 equalsignorecase (搜索) )
is to compare是比較
how about the right this??如何正確的這嗎?
if (arr3[u] NOT EQUAL TO (search));如果( arr3 [ u ]不等於(搜索) ) ;
what is tha code for that??什麼是臨屋區碼是什麼? ?