I have got one class with various member variables. There is a constructor and there are getter-methods, but no setter-methods. In fact, this object should be immutable.
public class Example {
private ArrayList<String> list;
}
Now I noticed the following: when I get the variable list with a getter-method, I can add new values and so on – I can change the ArrayList. When I call the next time get() for this variable, the changed ArrayList is returned. How can this be? I didn’t set it again, I just worked on it!
With a String this behaviour isn’t possible. So what is the difference here?
Just because the reference to the list is immutable doesn’t mean that the list it refers to is immutable.
Even if
listwas madefinalthis would be allowedbut this would not allowed:
In order to make the list immutable (prevent also the first line), I suggest you use
Collections.unmodifiableList:(Note that this creates an unmodifiable view of the list. If someone is holding on to the original reference, then the list can still be modified through that.)
That is because a
Stringis already immutable (unmodifiable) just as the list would be if you turned it into an unmodifiableList.Comparison: