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

编程入门 行业动态 更新时间:2024-10-26 02:28:47
本文介绍了为什么不能字符串是可变的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?

本文发布于:2023-11-06 09:56:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563375.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Java   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!