Search code examples
javaintellij-ideacollectionsgetter-settercode-inspection

Return of collection field warning - Setters and Constructors


IntelliJ warns me about "Return of collection field" if I do something like

private List<String> myList;

public List<String> getMyList() {
    return myList;
}

The description of the code-inspection states:

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.

I totally understand the problems but I wonder why I'm not warned about doing the same for setters and constructors

public MyListClass (List<String> myList) {
    this.myList = myList;
}

public void setMyList (List<String> myList) {
    this.myList = myList;
}

which I think can lead to the same problems.

Shouldn't I create new Collections for both getting and setting the Collection? So not only

return new ArrayList<String>(this.myList);

but also

this.myList = new ArrayList<String>(myList);

(Ignoring making returned lists unmodifiable or checking for null in this example)


Solution

  • You can use the Java | Assignment issues | Assignment to Collection or array field from parameter inspection to get warnings in setters and constructors too.