-
Notifications
You must be signed in to change notification settings - Fork 784
2019-09-24:String为什么要设计成不可变的? #153
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
安全,常量,hashCode |
安全(考虑类加载的关系,多线程使用时) |
因为String设计成不可变主要是考虑性能和安全. |
1,字符串常量池的需要 当创建一个 String 对象时,如果此字符串已经存在于常量池中,则不会创建一个新的对象,而是引用已经存在的对象 如果允许改变,那么将导致各种逻辑错误,比如改变一个对象将会影响另一个独立对象,严格来说,这种常量池的思想是一种优化手段 2,允许String对象缓存 HashCode java 中 String 对象的哈希码会被频繁的使用,比如在 hashMap中。字符串的不变形保证了hash码的唯一性,因此可以放放心的进行缓存。这也是一种优化手段,意味着不必没说都计算新的哈希码。在 String 类中有 private int hash 来缓存hashcode 3,安全性 String 被许多的类来当做参数,如 网络url,文件路径path 等等,如果String 不是固定的,将会引起各种安全隐患 |
性能优化(常量池存储,字符串不变保证了Hashcode唯一性) |
No description provided.
The text was updated successfully, but these errors were encountered: