开发者

Any foreseeable problem in having a mutator for a collection that accepts a new collection?

开发者 https://www.devze.com 2023-04-04 11:02 出处:网络
As per the title, are there any smells surrounding the provision of a setter that accepts a List instantiation for assignment to a instance variable?

As per the title, are there any smells surrounding the provision of a setter that accepts a List instantiation for assignment to a instance variable?

i.e.

public class Test{
    private List<St开发者_运维技巧ring> strings;

    public Test() {}

    public void setStrings(List<Strings> strings) {
        this.strings = strings;
    }
}

What could be a better approach (domain specifics aside)?


The problem with your code is that the caller of your setter can modify the list, because the caller still has a reference. Consider this code:

Test test = new Test();
List<String> list = new ArrayList<String>();
test.setStrings(list);
list.clear(); // oops! the state of Test has changed without Test knowing!

The better approach is to use a copy of the list:

public void setStrings(List<Strings> strings) {
    this.strings = new ArrayList<String>(strings);
}


This fine (I assume you have a getter as well) The only thing I might do differently is take a copy of the list rather than a direct assignment.

public void setStrings(List<Strings> strings) {
    this.strings = new ArraysList<String>(strings);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消