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?
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.
You shouldn't provide variable of type ArrayList
. Provide just List
and make sure the getter does one of the next:
or both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With