I have a list which is a private member in my class. I have used getter and setter to get and set the values. SOnar throws an error - Mutable members should not be stored or returned directly.
For example: ABC and DEF are two classes.
class ABC{
private List<DEF> defList;
public List<DEF> getDefList() { return defList; }
public void setDefList(List<DEF> defList) { this.defList = defList; }
After lot of googling and searching, I have understood that the getter can be changed as follows:
public List<DEF> getDefList() { return new ArrayList<>(defList); }
When i try to use setter similarly,
public void setDefList(List<DEF> defList) { this.defList.addAll(defList); }
then the variable starts showing
'private field 'defList' is never assigned.
May I know the correct way to do when it is a list, (a list of another class)
Note: Both the answers from Prasad Karunagoda and Leo Aso works. I cant mark both as accepted answer. So having a note here
The warning is because you did not give the field an initial value. This is how you should implement the code to ensure immutability using java.util.Collections
.
class ABC {
private List<DEF> defList = Collections.emptyList();
public List<DEF> getDefList() {
return defList;
}
public void setDefList(List<DEF> defList) {
// defensively copy, then make immutable
defList = new ArrayList<>(defList);
this.defList = Collections.unmodifiableList(defList);
}