2012-04-06 79 views
0

有大約Stringz例如一個簡單的問題在Java中正在創建多少個對象?

池如果我有這樣的情況: 方案1:

String s1 = "aaa"; 
String s2 = new String("aaa"); 

,然後翻轉 方案2:

String s1 = new String("aaa"); 
String s2 = "aaa"; 

在每種情況 - 在字符串池和堆中創建了多少個對象? 我假設兩者都會創建相同數量的對象(2個對象 - 字符串池中每個場景中兩條線的單個「aaa」,以及新操作符的一個)。 我在iview被告知這是不正確的 - 我很好奇我的理解有什麼問題?

+1

這是什麼語言? – EdChum 2012-04-06 14:54:04

+0

我的不好 - 這是在Java! – 2012-04-06 15:05:38

+0

其實,這是正確的解釋: http://stackoverflow.com/questions/1881922/questions-about-javas-string-pool – evanwong 2012-04-06 15:11:11

回答

1

文字"aaa"的字符串在加載類時創建併合並,因此只有當您的兩行代碼被執行時纔會創建一個新字符串。

要清楚:兩個示例在執行時只會創建一個新的String對象。在第一次使用包含字符串「aaa」的類時創建該文字。

class FooBar{ 
    void foo(){ 
    String s1 = "aaa";//the literal already exists 
    String s2 = new String("aaa");//creates string for s2 
    } 
    void bar(){ 
    String s1 = new String("aaa"); //creates string for s1 
    String s2 = "aaa";//the literal already exists 
    } 
} 

class Test{ 

    public void main(String... args){ 
     ... 
     //first time class FooBar used in program, class with literals loaded 
     FooBar fb = new FooBar(); 
     //creates one string object, the literal is already loaded 
     fb.bar(); 
     //also creates one string object, the literal is already loaded 
     fb.foo(); 
    } 
} 
+0

你可能在技術上是正確的,但你能否更詳細地解釋究竟發生了什麼時間? – 2012-04-06 16:10:52

+0

你是否暗示在這兩種情況下?像邁克爾說,你能不能詳細說明一下? – 2012-04-06 16:27:17

1

答案是,正如你在接受採訪時表示堆中在這兩種情況下字符串池1個實例和1。

字符串可以存在兩個空格:堆和存儲interned字符串的perm gen。

String構造函數在堆中創建一個String。字符串文字是在永久生成的字符串池中創建的。堆中的字符串可以通過方法String.intern()移動到字符串池中,該方法實現字符串(即,確定對池中相等字符串的引用,或者在那裏創建一個相同的字符串,如果沒有),並返回一個引用到interned字符串。

編輯:要檢查我已回答的問題,請將System.out.println(s1 == s2);作爲第三行添加到每個示例中。它會在兩種情況下都打印出錯誤,證明兩個對象具有不同的內存地址。

+0

投票瞭解得好解釋的答案 – gifpif 2015-01-20 07:36:00