具有ArrayList成员变量的不可变对象 - 为什么可以更改此变量? [英] Immutable Object with ArrayList member variable - why can this variable be changed?

查看:272
本文介绍了具有ArrayList成员变量的不可变对象 - 为什么可以更改此变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含各种成员变量的类。有一个构造函数,有getter方法,但没有setter方法。实际上,这个对象应该是不可变的。

I have got one class with various member variables. There is a constructor and there are getter-methods, but no setter-methods. In fact, this object should be immutable.

public class Example {
   private ArrayList<String> list; 
}

现在我注意到以下内容:当我获得带有getter的变量列表时 - 方法,我可以添加新的值等等 - 我可以更改 ArrayList 。当我为下一次 get()调用此变量时,将返回更改的 ArrayList 。怎么会这样?我没有再设置它,我只是努力了!
如果使用 String ,则无法执行此操作。那么这里的区别是什么?

Now I noticed the following: when I get the variable list with a getter-method, I can add new values and so on - I can change the ArrayList. When I call the next time get() for this variable, the changed ArrayList is returned. How can this be? I didn't set it again, I just worked on it! With a String this behaviour isn't possible. So what is the difference here?

推荐答案

仅仅因为列表中的引用是不可变的而不是' t表示它引用的列表是不可变的。

Just because the reference to the list is immutable doesn't mean that the list it refers to is immutable.

即使 list 是发了 final 这是允许的

// changing the object which list refers to
example.getList().add("stuff");

但这允许:

// changing list
example.list = new ArrayList<String>();   // assuming list is public






为了制作列表不可变(也防止第一行),我建议你使用 Collections.unmodifiableList

public class Example {
    final private ArrayList<String> list;

    Example(ArrayList<String> listArg) {
        list = Collections.unmodifiableList(listArg);
    }
}

(请注意,这会创建列表的不可修改的视图如果有人持有原始参考,那么仍然可以修改该列表。)

(Note that this creates an unmodifiable view of the list. If someone is holding on to the original reference, then the list can still be modified through that.)


使用String这种行为是不可能的。那么这里的区别是什么?

With a String this behaviour isnt possible. So what is the difference here?

那是因为 String 已经是不可变的(不可修改的),就像你将它变成一个不可修改的列表一样。

That is because a String is already immutable (unmodifiable) just as the list would be if you turned it into an unmodifiableList.

比较:

              String data structure  | List data structure
           .-------------------------+------------------------------------.
Immutable  | String                  | Collection.unmodifiableList(...)   |
-----------+-------------------------+------------------------------------|
Mutable    | StringBuffer            | ArrayList                          |
           '-------------------------+------------------------------------'

这篇关于具有ArrayList成员变量的不可变对象 - 为什么可以更改此变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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