Useful factory for defensive copying (short-circuit with new immutable collections)
Daniel Latrémolière
daniel.latremoliere at gmail.com
Wed Jan 11 17:26:16 UTC 2017
In a library, when you receive externally an object at construction of
one of your class and mandate it to be immutable, you need to make a
defensive copy. Given new immutable collections, it would be useful to
have a factory for defensive copy, doing nothing if object to be copied
is already an immutable collection (List, Set, Map), e.g. with a Map:
public static <K,V> Map<K,V> ofEntries(Map<K,V> map) {
// short-circuit if already an immutable Map
if (map.getClass().getDeclaringClass() == java.util.ImmutableCollections.class) {
return map;
}
// if mutable, then make an immutable copy
Map.Entry[] entries = new Map.Entry[map.size()];
int i = 0;
for(Map.Entry<K,V> entry : map.entrySet()) {
entries[i] = Map.entry(entry.getKey(), entry.getValue());
i += 1;
}
return Map.ofEntries(entries);
}
--
Thanks,
Daniel.
More information about the core-libs-dev
mailing list