为什么String类要这样设计呢?
为什么 String
类的设计方式是该类的实例被池化且不可变?
谢谢&问候, 维迪亚卡·夏尔马。
Why was the String
class designed in a way that instances of this class are pooled as well as immutable?
Thanks & Regards,
Vidyakar Sharma.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
字符串对象通常不会被池化 - 只有字符串常量会通过实习自动池化。 (当然,您可以手动调用
intern
,甚至可以通过HashSet
等创建您自己的池。)这只是安全的因为字符串是不可变的 - 确保任何编译时常量仅在内存中出现一次是有意义的。您不想为系统中的每个字符串在实习池中查找字符串(或永远保留它)付出代价,因为随着时间的推移可能会有许多不同的字符串。然而,只要这些类存在,从类加载的字符串常量就会一直存在,并且通过将它们驻留一次,您可以减少 GC 流失所需的内存。
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 viaHashSet<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.
如果 String 不是不可变的,那么您将无法
简而言之,生活会变得更加复杂,因为你必须在各处制作 String 的防御性副本,并且 StackOverflow 会充斥着有关微妙错误的问题,其中某些 String 存储在映射中但无法再找到。
If String weren't immutable you wouldn't be able
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.
不可变对象是现有的最佳设计决策之一。它的目的是简化并发编程。共享该对象的线程不能互相干扰。
如果您想要可变字符串,请查看:StringBuffer 和 StringBuilder
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
对于可变字符串,请查看:java.lang 中的 StringBuffer 和 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.