不可变的是什么意思? [英] What is meant by immutable?

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

问题描述

这可能是有史以来最愚蠢的问题,但我认为这对新手来说完全是混乱。

This could be the dumbest question ever asked but I think it is a total confusion for a newbie.


  1. 有人可以澄清 immutable 的含义吗?

  2. 为什么字符串不可变?

  3. 不可变对象有哪些优点/缺点? ?

  4. 为什么像 StringBuilder 这样的可变对象优先于String而不是反之?

  1. Can somebody clarify what is meant by immutable?
  2. Why is a String immutable?
  3. What are the advantages/disadvantages of immutable objects?
  4. 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屋!

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