2014-03-30 33 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 
    } 
} 
相关问题