Is there any difference between these two ways of adding a list to the bean property?
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.
With method 2, you would just add all new entries to the already existing list instance.
In first method , the whole of stringList
is initialized with provided list . But in second method , all the elements of new list are added to existing stringList
.
Yes, there is a big difference, and first approach is correct. Here's why:
set
the list rather than adding the elements. If you want to add
, you can expose another method like 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) Read more on getters
and setters
here .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.