Skip to content
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

2019-09-24:String为什么要设计成不可变的? #153

Open
MoJieBlog opened this issue Sep 24, 2019 · 5 comments
Open

2019-09-24:String为什么要设计成不可变的? #153

MoJieBlog opened this issue Sep 24, 2019 · 5 comments
Labels

Comments

@MoJieBlog
Copy link
Collaborator

No description provided.

@DaveBoy
Copy link

DaveBoy commented Sep 24, 2019

安全,常量,hashCode
即安全和性能

@Petterpx
Copy link

安全(考虑类加载的关系,多线程使用时)
性能(常量池,hashcode)

@JianhuaWan
Copy link

因为String设计成不可变主要是考虑性能和安全.
性能是String为常量池,hashcode
安全是在多线程使用是他是线程安全的.

@LvKang-insist
Copy link

1,字符串常量池的需要

​ 当创建一个 String 对象时,如果此字符串已经存在于常量池中,则不会创建一个新的对象,而是引用已经存在的对象

​ 如果允许改变,那么将导致各种逻辑错误,比如改变一个对象将会影响另一个独立对象,严格来说,这种常量池的思想是一种优化手段

​ 2,允许String对象缓存 HashCode

​ java 中 String 对象的哈希码会被频繁的使用,比如在 hashMap中。字符串的不变形保证了hash码的唯一性,因此可以放放心的进行缓存。这也是一种优化手段,意味着不必没说都计算新的哈希码。在 String 类中有 private int hash 来缓存hashcode

​ 3,安全性

​ String 被许多的类来当做参数,如 网络url,文件路径path 等等,如果String 不是固定的,将会引起各种安全隐患

@gabyallen
Copy link

性能优化(常量池存储,字符串不变保证了Hashcode唯一性)
安全性(考虑类加载的关系,多线程使用时,网络请求时url地址)

@Moosphan Moosphan added the Java label Sep 25, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

7 participants