不可变的是什么意思? [英] What is meant by immutable?
问题描述
这可能是有史以来最愚蠢的问题,但我认为这对新手来说完全是混乱。
This could be the dumbest question ever asked but I think it is a total confusion for a newbie.
- 有人可以澄清 immutable 的含义吗?
- 为什么
字符串
不可变? - 不可变对象有哪些优点/缺点? ?
- 为什么像
StringBuilder
这样的可变对象优先于String而不是反之?
- Can somebody clarify what is meant by immutable?
- Why is a
String
immutable? - What are the advantages/disadvantages of immutable objects?
- Why should a mutable object such as
StringBuilder
be preferred over String and vice-verse?
一个很好的例子(在Java中)将非常感激。
A nice example (in Java) will be really appreciated.
推荐答案
Immutable意味着一旦对象的构造函数完成执行,该实例就无法更改。
Immutable means that once the constructor for an object has completed execution that instance can't be altered.
这很有用,因为它意味着你可以传递对象的引用周围,不用担心别人会改变它的内容。 特别是在处理并发时,对于永不改变的对象没有锁定问题
This is useful as it means you can pass references to the object around, without worrying that someone else is going to change its contents. Especially when dealing with concurrency, there are no locking issues with objects that never change
例如
class Foo
{
private final String myvar;
public Foo(final String initialValue)
{
this.myvar = initialValue;
}
public String getValue()
{
return this.myvar;
}
}
Foo
不必担心调用者 getValue()
可能会更改字符串中的文本。
Foo
doesn't have to worry that the caller to getValue()
might change the text in the string.
如果您想要类似于 Foo
的类,但使用 StringBuilder
而不是字符串
作为成员,您可以看到调用者 getValue()
将能够改变 StringBuilder
Foo
实例的属性。
If you imagine a similar class to Foo
, but with a StringBuilder
rather than a String
as a member, you can see that a caller to getValue()
would be able to alter the StringBuilder
attribute of a Foo
instance.
还要注意你可能会发现的不同类型的不变性:埃里克利珀写了一博客文章。基本上你可以拥有其接口是不可变的但在幕后实际可变的私有状态的对象(因此不能在线程之间安全地共享)。
Also beware of the different kinds of immutability you might find: Eric Lippert wrote a blog article about this. Basically you can have objects whose interface is immutable but behind the scenes actual mutables private state (and therefore can't be shared safely between threads).
这篇关于不可变的是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!