Clause 5 assumes that at any time when you have any methods that return something that needs to be done with a mutable object, you must create a copy that is independent of the private state. For example:
public final class Foo { private final List<String> strings; public Foo(List<String> strings) {
Please note that protective copying is only required when the state is changed. For example, if you used an ImmutableList (e.g. from Guava) as the state in the above class, you would need to create a new list in the construct (unless the input is an ImmutableList ), but not in getStrings .
Also note that in this case, String is immutable, so we do not need to copy each line. If it was a List<StringBuilder> , we would need to create a new list and a new copy of each item as part of the protective copy. As you can see, life becomes easier when all your condition is also unchanged.
Jon Skeet Aug 17 '12 at 6:21 2012-08-17 06:21
source share