开发者

Why does Java string have a copy constructor? [duplicate]

开发者 https://www.devze.com 2022-12-12 09:09 出处:网络
This question already has answers here: Closed 13 years ago. Possible Duplicate: What is the purpose of the expression “new St开发者_如何转开发ring(…)” in Java?
This question already has answers here: Closed 13 years ago.

Possible Duplicate:

What is the purpose of the expression “new St开发者_如何转开发ring(…)” in Java?

It's immutable, why would you need to invoke String.String(String str) ?


From the API doc:

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

The only reason I can think of is in the situation where:

  1. You've created a very large String: A.
  2. You've created a small substring: B based on A. If you look at the implementation of substring you'll see it references the same char[] array as the original string.
  3. String A has gone out of scope and you wish to reduce memory consumption.
  4. Creating an explicit copy of B will mean that the copy: B' no longer references the large char[]. Allowing B to go out of scope will allow the garbage collector to reclaim the large char[] that backs A and B, leaving only the small char[] backing B'.


new String(s) can help garbase collection:

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


Just in case you need String that are not the same but equal.

Maybe for testing to make sure, people really do str.equals(str2) instead of (str == str2). But I never needed it.

0

精彩评论

暂无评论...
验证码 换一张
取 消