public void setMyArray(String[] array) {
this.array = array;
}
Solution
public void setMyArray1(String[] newArray) {
if(newArray == null) {
this.newArray = new String[0];
} else {
this.newArray = Arrays.copyOf(newArray, newArray.length);
}
}
Why should we avoid to store array directly?
Array stored by your object also held by the caller and the caller subsequently modifies this array, the array stored in the object (and hence the object itself) will change.
The solution is to make a copy within the object when it gets passed. This is called defensive copying. A subsequent modification of the collection won't affect the array stored within the object.
It's also good practice to normally do this when returning a collection. Otherwise the receiver could perform a modification and affect the stored instance.
Note
This obviously applies to all mutable collections (and in fact all mutable objects) - not just arrays. Note also that this has a performance impact which needs to be assessed alongside other concerns.
No comments:
Post a Comment