2013-08-23 35 views
-1

我有我無法理解的代碼。在開始時你可以看到兩個相同的字符串,並且當我使用運算符==進行比較時,它說這是真的,與equals()方法相同,但是當我在運行時運算符中創建兩個相同的字符串==表示爲false。這是爲什麼發生?Java:字符串不變性和運算符==

這是否意味着當我對相同的字符串進行硬編碼時,它們被放置在內存中的相同位置並且兩個引用指向它?我發現類似的question,但沒有明確的答案。

public class StringTesting { 
    public static void main(String[] args){ 
     String string1 = "hello";     //\ 
                // } same place in the memory ? 
     String string2 = "hello";     /// 

     System.out.println(string1 == string2);  //true 
     System.out.println(string1.equals(string2));  //true 

     String string3 = "hey"; 
     String string4 = "he"; 

     System.out.println(string3 == string4);   //false 
     System.out.println(string3.equals(string4));  //false 

     string4 += "y"; 

     System.out.println(string3 == string4);   //false ???? 
     System.out.println(string3.equals(string4));  //true 

     System.out.println(string3 + " " + string4);  //hey hey 
    } 
} 
+5

如果你去到[這裏](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java),你會找到你所有的答案。 –

+1

您的粗體文本正在發生什麼 –

+2

@RichardTingle Nice rep。儘管如此,我仍想毀掉它:P。 –

回答

4

下述化合物賦值操作符:

string4 += "y"; 

在運行時執行字符串連接。由於string4的值僅在運行時進行評估。在運行時完成的字符串連接創建一個新對象。

JLS Section 3.10.5(參見實現這一節的末尾):

字符串在運行時通過串聯計算新創建,並因此是不同的。

但是,如果您執行兩個字符串文字的連接,它將不會創建不同的對象。所以下面的代碼將返回true

"he" + "y" == "hey"; 

這JLS節包含了各種字符串連接示例代碼段:

String hello = "Hello", 
String lo = "lo"; 

System.out.print((hello == "Hello") + " ");   // true 
System.out.print((Other.hello == hello) + " ");  // true 
System.out.print((other.Other.hello == hello) + " ");// true 
System.out.print((hello == ("Hel" + "lo")) + " ");  // true 
System.out.print((hello == ("Hel" + lo)) + " ");  // false 
System.out.println(hello == ("Hel" + lo).intern()); // true 
+0

另外,與'公共靜態最終字符串he0 =「他」; public static String he1 =「he」;','he0 +「y」==「hey」&& he1 +「y」!=「hey」'即使he0移入不同的編譯單元也是如此。 –

+0

@MikeSamuel。當然。感謝您指出了這一點。錯過了我的答案。 :) –

0

string4 += "y";創建一個新的對象。

然而,字符串文字作爲優化放置在內存中的相同位置(這稱爲string interning)。

0

string1string2string3都是字符串常量。即它們在.class文件中表現爲常量池條目。在Java中,字符串常量是被執行的。

string4是一個新字符串,通過取字符串常量"he",然後附加"y"創建。因此,它不是一個字符串常量,也不是實際的。

這就是爲什麼string3 != string4