1
public Map<String, List<Integer>> deepCopy(Map<String, List<Integer>> map) {
    Map<String, List<Integer>> res = new HashMap<>();
    for (String s : map.keySet()) {
        res.put(s, map.get(s));
    }
    return res;
}

This method is to make a deep copy of a map. I believe there's some problems in the method I wrote, but I couldn't find out

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
xunmiw
  • 31
  • 3

2 Answers2

1
res.put(s, map.get(s));

you don't create a copy of the original List. It is still the same Object and the "copied" object will be affected by mutation of the original Object.

Also you don't create a copy of the Strings, the keys of the Map. The Strings in your copied Map will have the same reference.

Simulant
  • 18,114
  • 7
  • 59
  • 94
0

The easiest was is to do it like this:

res.put(s, new ArrayList<>(map.get(s));

this way you don't copy the reference to the list but you are creating a new list, hence a deep copy.

John Kugelman
  • 330,190
  • 66
  • 504
  • 555
taygetos
  • 2,835
  • 2
  • 19
  • 26