开发者

Why String class was designed this way?

Why was the String class designed in a way that instances of this class are pooled as well 开发者_运维问答as immutable?

Thanks & Regards, Vidyakar Sharma.


String objects aren't usually pooled - only string constants are pooled automatically via interning. (You can call intern manually of course, or even create your own pools via HashSet<String> etc.) This is only safe because strings are immutable - and it makes sense to make sure that any compile-time constant only occurs once in memory.

You wouldn't want to pay the price of looking up the string in the intern pool (or keeping it around forever) for every string in the system, because there may be many different strings over time. However, the string constants loaded from classes will stick around as long as those classes do, and by interning them once you can reduce the memory required as GC churn.


If String weren't immutable you wouldn't be able

  • to safely return a String field from a getter without breaking encapsulation, because the caller might modify the contents of the string behind your back
  • to share a String between threads, because some thread might modify its content. All the accesses to the String would have to be synchronized.
  • to use Strings as keys in HashMaps/TreeMaps, because someone might change its value and thus its hashCode/comparison order
  • to pool Strings in order to have a single instance of the same constant string
  • to have a substring sharing the same char array of its string

In short, life would be much more complicated, because you would have to make defensive copies of the String everywhere, and StackOverflow would be flooded with questions regarding subtle bugs where some String is stored in a map but can't be found anymore.


An Immutable object is one of the best design decisions that exists. It's intended to simplify concurrent programming. Threads sharing the object can not interfere with each other.

If you want mutable strings check out: StringBuffer and StringBuilder


for mutable strings check out: StringBuffer and StringBuilder from java.lang.


Pooled to avoid having duplicate objects that represent the same.

Immutable to make it easier to share it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜