5

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?

gnat
  • 6,213
  • 108
  • 53
  • 73
Milan Mendpara
  • 3,091
  • 4
  • 40
  • 60
  • 2
    See http://stackoverflow.com/questions/8892350/immutable-vs-unmodifiable-collection – Zaki Jan 25 '12 at 16:18
  • 1
    See also Joshua Bloch's "Effective Java", Item 24: Make defensive copies when needed. The chapter is available online [here](http://www.informit.com/articles/article.aspx?p=31551&seqNum=2) – mike9322 Jan 25 '12 at 16:34
  • If you class is supposed to be all-immutable, save the reference to the list _in your class_ (after copying) as an instance of `UnmodifiableList`. No (additional) defensive copies needed, and it prevents _your_ class from modifying it, during maintenance. – Clockwork-Muse Jan 25 '12 at 17:23

3 Answers3

3

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.

Sergey Grinev
  • 34,078
  • 10
  • 128
  • 141
3

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.

Steve McLeod
  • 51,737
  • 47
  • 128
  • 184
0

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.

Erhan Bagdemir
  • 5,231
  • 6
  • 34
  • 40