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

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

问题描述

这可能是有史以来最愚蠢的问题,但我认为对于 Java 新手来说,这很令人困惑.

This could be the dumbest question ever asked but I think it is quite confusing for a Java newbie.

  1. 有人能解释一下不可变是什么意思吗?
  2. 为什么 String 是不可变的?
  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 the 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 而不是 String 作为成员,您可以看到getValue() 的调用者将能够改变 Foo 实例的 StringBuilder 属性.

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.

还要注意您可能会发现的不同类型的不变性:Eric Lippert 写了一篇 博客文章 关于这个.基本上,您可以拥有接口不可变的对象,但在幕后实际可变的私有状态(因此不能在线程之间安全共享).

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天全站免登陆