Search code examples
javacollectionsjavabeans

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)

Solution

  • 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.