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.

Reply via email to