It looks like you can just use putAll
:
public void addProperties(Map<String, Object> propertyMap) {
this.propertyMap.putAll(propertyMap);
}
This is called "defensive copying". What happens here is the values in the local propertyMap
are copied into the instance's propertyMap
. A weakness here is that changes the given propertyMap
aren't going to be reflected in the instance's propertyMap
. This is essentially creating a snapshot of the given map and copying that snapshot to the instance field map.
There are other ways of creating defensive copies as well, including clone()
and the HashMap(Map)
constructor.
For immutable collections, the unmodifiable methods in Collections
will return collections that throw exceptions when you try to add to them. For example,
Set<String> strs = Collections.unmodifiableSet(new HashSet<String>());
strs.add("Error"); // This line throws an exception
Immutable collections protect their values by disallowing modification (removing and adding) while defensive copies protect their values by not referencing the copied collection (in other words, changes in the original collection aren't shown in the copy).