Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

immutability of a class when an instance variable present as arraylist

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?

like image 944
Milan Mendpara Avatar asked Jan 25 '12 16:01

Milan Mendpara


2 Answers

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.

like image 134
Steve McLeod Avatar answered Nov 15 '22 05:11

Steve McLeod


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.

like image 28
Sergey Grinev Avatar answered Nov 15 '22 05:11

Sergey Grinev