I have a question about immutability of a class.
How can I ensure the immutability of a class when an arraylist is one of the member variable in it?
Lets say we have a getter method for a member variable for which the type is 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 somebody please explain this concept in details?
There are two ways this is usually solved:
1) Return a copy:
2) Returns an unmodifiable view:
Of course neither option guards against the List elements being mutable. If that's the case you will need to make a copy of the List that contains copies of the elements.
Mahesh Kedari wrote: Lets say we have a getter method for a member variable for which the type is 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.
If you are directly returning reference by getter method, then the class is not immutable.
Your getter method must not return the reference to any mutable object. If the object is mutable, create a copy of it (copy of whole object, not just reference - e.g. Collections.copy(arrayList1,arrayList2)) and return it. That way, even if you modify the returned object outside getter method, you'll be modifying a copy of instance variable, and not actual member of the class.