2014-03-30 34 views
0

這裏是我的主類爲什麼在這裏字符串字面不被禁用?

public class MainClass { 
public static void main(String args[]) { 
    String str1 = "testString"; 
     String str2 = "testString" + 1; //line1 
     //above literal value(i.e str2 = "testString1") is interned and stored in permamnent generation space 
     //now when whenever i create "testString1" down the line in this program, it should refer from same location 
     //but it does not seem true 
     TestThread tt= new TestThread(str1, str2); 
     tt.start(); 

     } 

} 

這裏是我的線程類

package Test; 

public class TestThread extends Thread { 
    String str2; 

public TestThread(String str3, String str4) { 
     this.str3 = str3 + 1; //line2 
     System.out.println("value inside Thread is "+this.str3); 
     System.out.println("value inside Thread is "+str4); 
     if(str3 == str4){ 
      System.out.println("Yes they are equal"); 
     }else{ 
     System.out.println("They are not equal"); 
     } 

     //line 3 


    @Override 
    public void run(){ 
     // some processing   
     } 
} 

在第3行, 「他們是不是等於」 被打印出來。但爲什麼 ?第2行應該引用與第1行相同的字符串,因爲我使用的字符串文字 被interned並存儲在permgen空間中。

更新: -有沒有一種方法可以強制編譯器使用字符串文字,而不是優化代碼使用新的字符串?

回答

1
this.str3 = str3 + 1; //line2 

您在運行時使用連接,它始終創建一個默認情況下不會實現的新String。您可以使用intern()方法,然後嘗試進行比較。

String str2 = "testString" + 1; //line1 

這是一個compile time constant expression和編譯成功將被轉換爲

String str2 = "testString1"; 

這是一個字符串文字,將被拘留。現在在你的run方法中,你正在創建一個新的字符串,正如我前面所解釋的因此兩者都指向不同的字符串實例,因此==會給你錯誤。

0

如果你看一下反編譯的代碼,你應該看到下面的代碼在第2行的編譯器嘗試優化代碼

this.str3 = (new StringBuilder(String.valueOf(str3))).append(1).toString(); 

所以最後它創造新的運營商新的String對象,同時的toString()

+0

有沒有辦法我可以強制編譯器使用字符串文字而不是優化代碼來使用新的字符串? – user3198603

+0

否。可以使用第3行沒有字符串文字。 – Jorn

1

您需要使用String類的intern()方法來獲得期望的結果,這裏是你的TestThread的工作示例:

public class TestThread extends Thread { 
    String str3; 

    public TestThread(String str3, String str4) { 
    this.str3 = str3 + 1; //line2 
    System.out.println("value inside Thread is "+this.str3); 
    System.out.println("value inside Thread is "+str4); 
    if(this.str3.intern() == str4.intern()){ 
     System.out.println("Yes they are equal"); 
    }else{ 
     System.out.println("They are not equal"); 
    } 
    } 

    @Override 
    public void run(){ 
    // some processing 
    } 
} 
相關問題