java - 为什么字符串在 Java 和 .NET 中不能是可变的?

标签 java .net string mutable

为什么他们决定让 String 在 Java 和 .NET(以及其他一些语言)中不可变?他们为什么不让它可变呢?

最佳答案

根据Effective Java ,第 4 章,第 73 页,第 2 版:

"There are many good reasons for this: Immutable classes are easier to design, implement, and use than mutable classes. They are less prone to error and are more secure.

[...]

"Immutable objects are simple. An immutable object can be in exactly one state, the state in which it was created. If you make sure that all constructors establish class invariants, then it is guaranteed that these invariants will remain true for all time, with no effort on your part.

[...]

Immutable objects are inherently thread-safe; they require no synchronization. They cannot be corrupted by multiple threads accessing them concurrently. This is far and away the easiest approach to achieving thread safety. In fact, no thread can ever observe any effect of another thread on an immutable object. Therefore, immutable objects can be shared freely

[...]

同一章节的其他小点:

Not only can you share immutable objects, but you can share their internals.

[...]

Immutable objects make great building blocks for other objects, whether mutable or immutable.

[...]

The only real disadvantage of immutable classes is that they require a separate object for each distinct value.

关于java - 为什么字符串在 Java 和 .NET 中不能是可变的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/93091/

相关文章:

java - 在 Android 中保存之前保留数据

c# - 什么时候可以不调用 Application_EndRequest?

.net - 内存随机化作为应用程序安全增强?

Python "join"位于字符串两侧?

c - 严格的性能实现

javascript - JS 正则表达式匹配方括号中最后一次出现的数字

java - java中写入excel时出现错误

java - JSP中HashMap中的重复键

java - libgdx 如何检测冲突?

c# - 如果你改变它们的身份,HashSets 不会保持元素的唯一性