immutability of a class when an instance variable present as arraylist

老子叫甜甜 提交于 2019-12-07 06:49:30

问题


I have a class which is immutable

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?


回答1:


You are indeed right. Immutability is violated.

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.




回答2:


You shouldn't provide variable of type ArrayList. Provide just List and make sure the getter does one of the next:

  1. returns a copy of your list
  2. or returns unmodifiable list

or both.




回答3:


if you create a new instance of that changed object of type X, then instance of X would be considered as immutable. It is easier to understand if you consider your ArrayList. YOu've methods to alter this list. Each altering method make a copy of this list and add/removes/updates on the new copy and return back.



来源:https://stackoverflow.com/questions/9006040/immutability-of-a-class-when-an-instance-variable-present-as-arraylist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!