为什么 String 类是final的?
在我的编程生涯中,有很多时刻我希望 String 类不是final/sealed/NotInheritable。
语言架构师试图阻止我做什么,这会给工作带来麻烦。
相反,语言架构师希望通过限制我扩展 String 类来阻止我投入工作,到底是什么?
您能列出可扩展字符串类的优缺点吗?
Possible Duplicate:
Why is String final in Java?
There are various moments in my programming life that I wished the the String class had not been final/sealed/NotInheritable.
What are the language architects trying to prevent me from doing that would throw a monkey wrench into the works.
Rather, what are the monkey wrenches the language architects would want to prevent me from throwing into the works by restricting me from extending String class?
Could you list a list of pros-cons of extendable string class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
String 是一个不可变类,这意味着您在创建它后无法修改其状态。如果您可以在字符串进入另一个库或地图(例如地图)后对其进行修改,则结果将是不可预测的。
Java API 的一个错误是
BigInteger
和BigDecimal
不是最终的,这意味着当从不可信代码接收这些对象时,您需要执行这些对象的防御性副本。相反,您始终可以相信String
将保持一致。不可信的 BigInteger:
对于
String
来说,同样的事情是不可能的。正如 Effective Java 中所述,您需要为这些类型的对象制作防御性副本:String is an immutable class which means if you cannot modify its state after you create it. If you could modify a string after it has entered another library, or a Map for instance the result would be unpredictable.
One mistake of the Java API is that
BigInteger
andBigDecimal
are not final which means you need to perform a defensive copy of these objects when receiving them from non trusted code. Conversely, you can always trust that aString
will remain consistent.Untrustworthy BigInteger:
The same thing is not possible with
String
. As stated in Effective Java, you need to make defensive copies of these types of objects:字符串是最终的,因为它代表不可变的数据类型。天真地扩展 String 会导致多种可怕的情况,因为有很多库依赖于 String 对象的不变性。
扩展 String 使其可变对于 Sting 通过的任何代码都是不可见的,但会产生非常令人惊讶和讨厌的副作用,例如突然无法从 HashMap 加载值,即使您确实拥有自 hashCode 以来的键的 String就会被劫持。
String is final because it represents an immutable data type. Manifold terribleness would result from extending String naively because there are lots of libraries that depend upon the immutability of String objects.
Extending String to make it mutable would be invisible to any code the Sting passes through, but would have very surprising and nasty side-effects like suddenly not being able to load values from HashMaps even though you literally have the String of the key since the hashCode would have been hijacked.