[英]Difference between using getter and setter methods to add list to a bean property?
Is there any difference between these two ways of adding a list to the bean property? 这两种向bean属性添加列表的方式之间有什么区别吗?
private List<String> stringList;
public List<String> getStringList() {
return stringList;
}
public void setStringList(final List<String> stringList) {
this.stringList = stringList;
}
setStringList(list of strings)
getStringList().addAll(list of strings)
If the list would already contain entries, those would be overwritten with method 1, because you set a completely new instance of the list. 如果列表中已经包含条目,则将使用方法1覆盖这些条目,因为您设置了一个全新的列表实例。
With method 2, you would just add all new entries to the already existing list instance. 使用方法2,您只需将所有新条目添加到已经存在的列表实例中。
In first method , the whole of stringList
is initialized with provided list . 在第一种方法中,整个
stringList
用提供的列表初始化。 But in second method , all the elements of new list are added to existing stringList
. 但是在第二种方法中,新列表的所有元素都添加到现有的
stringList
。
Yes, there is a big difference, and first approach is correct. 是的,有很大的不同,第一种方法是正确的。 Here's why:
原因如下:
set
the list rather than adding the elements. set
列表而不是添加元素。 If you want to add
, you can expose another method like addStrings()
add
,可以公开另一个方法,例如addStrings()
NullPointerException
if the list is null
(which it probably will be, if the object is newly created and the list
is not assigned any value) null
时抛出NullPointerException
(如果是新创建的对象,并且list
未分配任何值,则可能为NullPointerException
) Read more on getters
and setters
here . 在这里阅读更多关于
getters
和setters
信息 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.