简体   繁体   中英

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?

private List<String> stringList;

public List<String> getStringList() {
    return stringList;
}

public void setStringList(final List<String> stringList) {
    this.stringList = stringList;
}
  1. setStringList(list of strings)
  2. 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:

  • It's a setter method and hence, it should set the list rather than adding the elements. If you want to add , you can expose another method like addStrings()
  • Second approach would keep on adding the elements to the same list, ie if it's called 10 times with a list of 10 elements, the resultant list will have 100 elements which is not desirable
  • Second approach will throw a 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM