I have a getter that returns an unmodifiable list, as such:
public List<Product> getProductList() {
if (productList == null)
return new ArrayList<>();
return Collections.unmodifiableList(productList);
}
I am calling this getter as such:
List<Product> productList = new ArrayList<>(report.getProductList());
Then I pass this list to another method that modifies the list as such:
for (Product product : productList) {
product.addToAdvisoryList(advisory);
}
where addToAdvisoryList(Advisory advisory) is:
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);
}
}
After running these code, the original product list is modified. Can someone please explain what exactly happened? and what can be done to avoid modifying an unmodifiable list?