当实例变量作为arraylist存在时类的不变性 [英] immutability of a class when an instance variable present as arraylist

查看:152
本文介绍了当实例变量作为arraylist存在时类的不变性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个不可变的类

假设我有一个类型为ArrayList的成员变量的getter方法。在这种情况下,当我获得对该变量的引用时,我可以添加或删除它中的元素。在这种情况下,不变性似乎被违反。

Suppose I have a getter method for a member variable of type ArrayList. In that case when I get a reference to that variable, I can add or remove an element from it. In that case immutability seems to get violated.

任何人都可以详细解释这个概念吗?

Can anyone explain this concept in details?

推荐答案

你确实是对的。违反了不变性。

You are indeed right. Immutability is violated.

要使类不可变,您需要确保其所有getter都返回其状态可能发生更改的任何类的安全副本。

To make a class immutable, you need to make sure that all of its getters return safe copies of any class whose state could otherwise change.

这篇关于当实例变量作为arraylist存在时类的不变性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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