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

“String为什么不可变”解释勘误 #2461

Open
kiritozc opened this issue Aug 25, 2024 · 0 comments
Open

“String为什么不可变”解释勘误 #2461

kiritozc opened this issue Aug 25, 2024 · 0 comments

Comments

@kiritozc
Copy link

原文:
_String 真正不可变有下面几点原因:

  1. 保存字符串的数组被 final 修饰且为私有的,并且String 类没有提供/暴露修改这个字符串的方法。
  2. String 类被 final 修饰导致其不能被继承,进而避免了子类破坏 String 不可变。_

描述有误点:

  1. String不可变并不是因为String类被final修饰,因为byte[]数组被private修饰就已经能够保证不被子类继承后修改,并不需要给String加上final。
  2. String支持用数组进行初始化,如果仅仅是使用private修饰byte[]数组并不能阻止引用对应的值被修改。为了避免引用的值被修改,String在使用数组进行初始化时对值进行了复制,而非直接存储引用。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant