为什么不能字符串是可变的Java和.NET? [英] Why can't strings be mutable in Java and .NET?

查看:238
本文介绍了为什么不能字符串是可变的Java和.NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么他们决定使Java和.NET(和一些其他语言)字符串不变?他们为什么不让它可变的?

Why is it that they decided to make string immutable in Java and .NET (and some other languages)? Why didn't they make it mutable?

推荐答案

根据有效的Java ,第4章,第73页,第2版:

According to Effective Java, chapter 4, page 73, 2nd edition:

有许多很好的理由:不可变类更容易设计,实施和使用比可变类他们是不容易出错,而且更安全。

"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

[...]

在同一章的其他小点:

您不仅可以共享不可变对象,但你可以分享他们的内部。

不可变对象作出巨大积木其他对象,无论是可变的或不可变的。

一成不变的类的唯一真正的缺点是,它们需要为每个不同的值,一个单独的对象。

这篇关于为什么不能字符串是可变的Java和.NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆