简体   繁体   English

使用getter和setter方法将列表添加到bean属性之间的区别?

[英]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;
}
  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. 如果列表中已经包含条目,则将使用方法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: 原因如下:

  • It's a setter method and hence, it should set the list rather than adding the elements. 这是一个setter方法,因此,它应该set列表而不是添加元素。 If you want to add , you can expose another method like addStrings() 如果要add ,可以公开另一个方法,例如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 第二种方法是继续将元素添加到同一列表中,即,如果用10个元素的列表调用10次,则结果列表将包含100个元素,这是不希望的
  • 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) 第二种方法将在列表为null时抛出NullPointerException (如果是新创建的对象,并且list未分配任何值,则可能为NullPointerException

Read more on getters and setters here . 这里阅读更多关于getterssetters 信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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