Return 个 collection 个字段警告 - 设置器和构造函数
Return of collection field warning - Setters and Constructors
如果我做类似
的事情,IntelliJ 会警告我 "Return of collection field"
private List<String> myList;
public List<String> getMyList() {
return myList;
}
code-inspection 的描述状态:
Reports any attempt to return an array or Collection field from a method. Since the array or Collection may have its contents modified by the calling method, this construct may result in an object having its state modified unexpectedly. While occasionally useful for performance reasons, this construct is inherently bug-prone.
我完全理解这些问题,但我想知道为什么没有警告我对设置器和构造器做同样的事情
public MyListClass (List<String> myList) {
this.myList = myList;
}
public void setMyList (List<String> myList) {
this.myList = myList;
}
我认为这会导致同样的问题。
我不应该为获取和设置 Collection 创建新的 Collection 吗?所以不仅
return new ArrayList<String>(this.myList);
还有
this.myList = new ArrayList<String>(myList);
(在本例中忽略使返回列表不可修改或检查 null)
我相信这只是为了促进标准编码实践。
上面提到的警告会强制开发人员在 class 中使用不可变集合。
您可以安全地忽略此警告,或者您可以取消检查。
您可以在这里阅读:https://www.jetbrains.com/help/idea/2016.2/suppressing-inspections.html
您也可以使用 Java | Assignment issues | Assignment to Collection or array field from parameter
检查在 setter 和构造函数中获取警告。
如果我做类似
的事情,IntelliJ 会警告我 "Return of collection field"private List<String> myList;
public List<String> getMyList() {
return myList;
}
code-inspection 的描述状态:
Reports any attempt to return an array or Collection field from a method. Since the array or Collection may have its contents modified by the calling method, this construct may result in an object having its state modified unexpectedly. While occasionally useful for performance reasons, this construct is inherently bug-prone.
我完全理解这些问题,但我想知道为什么没有警告我对设置器和构造器做同样的事情
public MyListClass (List<String> myList) {
this.myList = myList;
}
public void setMyList (List<String> myList) {
this.myList = myList;
}
我认为这会导致同样的问题。
我不应该为获取和设置 Collection 创建新的 Collection 吗?所以不仅
return new ArrayList<String>(this.myList);
还有
this.myList = new ArrayList<String>(myList);
(在本例中忽略使返回列表不可修改或检查 null)
我相信这只是为了促进标准编码实践。
上面提到的警告会强制开发人员在 class 中使用不可变集合。
您可以安全地忽略此警告,或者您可以取消检查。
您可以在这里阅读:https://www.jetbrains.com/help/idea/2016.2/suppressing-inspections.html
您也可以使用 Java | Assignment issues | Assignment to Collection or array field from parameter
检查在 setter 和构造函数中获取警告。