2009-11-26 88 views
2

可能重複:
What is the purpose of the expression 「new String(…)」 in Java?爲什麼Java字符串有複製構造函數?

這是不可改變的,爲什麼你需要調用String.String(String str)

+0

重複http://stackoverflow.com/questions/334518/java-strings-string-s-new-stringsilly的? – VonC 2009-11-26 12:04:07

+1

Dupe:http://stackoverflow.com/questions/390703/what-is-the-purpose-of-the-expression-new-string-in-java,http://stackoverflow.com/questions/465627/use -of-the-stringstring-constructor-in-java – 2009-11-26 12:04:08

回答

3

新的String(S)可以幫助garbase集合:

String huge = ...; 
String small = s.substring(0,2); //huge.value char[] is not garbage collected here 
String gcFriendly = new String(small); //now huge.value char[] can be garbage collected 
+1

這是如何幫助垃圾收集的?這種方式會導致*更多*垃圾。 – 2009-11-26 12:06:21

+0

它有助於垃圾收集,如果你允許龐大,小到走出去的範圍爲gcFriendly不引用非常大的char []是備份既龐大而小。 – Adamski 2009-11-26 12:07:41

+0

接受這個,而不是簡單的因爲代碼示例的更詳細的答案。 – ripper234 2009-11-27 08:10:22

15

從API文檔:

Unless an explicit copy of original is needed, use of this constructor is 
unnecessary since Strings are immutable. 

我能想到的唯一原因是在情況:

  1. 你已經創建了一個非常大的String:A.
  2. 你」已經創建了一個小的子字符串:B基於A.如果你看看substring的實現,你會看到它引用相同的char []數組作爲原始字符串。
  3. String A已超出範圍,你想減少內存消耗
  4. 創建B的一個明確的副本將意味着副本:B」不再引用大char[]。允許B超出範圍將允許垃圾收集器收回支持A和B的大char[],僅留下小的char[]支持B'。
0

以防萬一你需要的字符串是不一樣的,但相等的。

也許爲了確保測試,人們確實做了str.equals(str2)而不是(str == str2)。但我從不需要它。