我有以下幾行代碼來比較字符串。 str1不等於str2,這是可以理解的,因爲它比較了對象引用。但爲什麼s1等於s2?什麼使參考比較(==)適用於Java中的某些字符串?
String s1 = "abc";
String s2 = "abc";
String str1 = new String("abc");
String str2 = new String("abc");
if (s1==s2)
System.out.println("s1==s2");
else
System.out.println("s1!=s2");
if (str1==str2)
System.out.println("str1==str2");
else
System.out.println("str1!=str2");
if (s1==str1)
System.out.println("str1==s1");
else
System.out.println("str1!=s1");
輸出:
s1==s2
str1!=str2
str1!=s1
你嘗試搜索SO第一? :( – 2012-03-14 17:44:28
http://stackoverflow.com/questions/7144059/java-string-pool-object-creation,http://stackoverflow.com/questions/4033625/if-compares-references-in-java-why-does -it-evaluate-to-true-with-these-strin,http://stackoverflow.com/questions/6377058/string-reference,http://stackoverflow.com/questions/1903094/java-strings-and-stringpool – 2012-03-14 17:45:56
(我沒有關閉這個,因爲我還沒有發現另一個問題*因爲這個焦點*,但我確信它存在) – 2012-03-14 17:49:17