Java Reference
In-Depth Information
Compliant Solution (Clone the Array)
This compliant solution defines a private array and a public method that returns a copy
of the array:
Click here to view code image
private static final String[] items = {/* . . . */};
public static final String[] getItems() {
return items.clone();
}
Because a copy of the array is returned, the original array values cannot be modified
by a client. Note that a manual deep copy could be required when dealing with arrays of
objects. This generally happens when the objects do not export a clone() method. Refer
to “OBJ06-J. Defensively copy mutable inputs and mutable internal components” [Long
2012], for more information.
Asbefore,thismethodprovidesdirectaccesstothearrayobjectsthemselves,butthisis
safebecause String isimmutable.Ifthearraycontainedmutableobjects,the getItems()
method could return an array of cloned objects instead.
Compliant Solution (Unmodifiable Wrappers)
This compliant solution declares a private array from which a public immutable list is
constructed:
Click here to view code image
private static final String[] items = {/* . . . */};
public static final List<String> itemsList =
Collections.unmodifiableList(Arrays.asList(items));
Neither the original array values nor the public list can be modified by a client. For
more details about unmodifiable wrappers, refer to Guideline 3 , “ Provide sensitive mut-
able classes with unmodifiable wrappers . ” This solution can also be used when the array
contains mutable objects.
Search WWH ::




Custom Search