我有一个getter,它返回一个不可修改的列表,例如:
public List<Product> getProductList() {
if (productList == null)
return new ArrayList<>();
return Collections.unmodifiableList(productList);
}
我这样称呼这个吸气剂:
List<Product> productList = new ArrayList<>(report.getProductList());
然后,我将此列表传递给另一个修改列表的方法,如下所示:
for (Product product : productList) {
product.addToAdvisoryList(advisory);
}
其中addToAdvisoryList(Advisory advisory)是:
public void addToAdvisoryList(Advisory advisory) {
if (advisoryList == null) {
setAdvisoryList(Collections.singletonList(advisory));
} else if (!isContainedAdvisory(advisoryList, advisory)) {
List<Advisory> newAdvisoryList = new ArrayList<>(advisoryList);
newAdvisoryList.add(advisory);
setAdvisoryList(newAdvisoryList);
}
}
运行这些代码后,原始产品列表将被修改。有人可以解释到底发生了什么吗?以及如何避免修改不可修改的列表?
侃侃无极
相关分类