September 2019
Intermediate to advanced
816 pages
18h 47m
English
A handy solution for performing a shallow copy of HashMap relies on the HashMap constructor, HashMap(Map<? extends K,? extends V> m). The following code is self-explanatory:
Map<K, V> mapToCopy = new HashMap<>();Map<K, V> shallowCopy = new HashMap<>(mapToCopy);
Another solution may rely on the putAll(Map<? extends K,? extends V> m) method. This method copies all of the mappings from the specified map to this map, as shown in the following helper method:
@SuppressWarnings("unchecked")public static <K, V> HashMap<K, V> shallowCopy(Map<K, V> map) { HashMap<K, V> copy = new HashMap<>(); copy.putAll(map); return copy;}
We can also write a helper method in Java 8 functional style as follows:
@SuppressWarnings("unchecked") ...