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
  • 349,597
  • 67
  • 533
  • 578
xunmiw
  • 21
  • 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
  • 19,190
  • 8
  • 63
  • 98
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
  • 349,597
  • 67
  • 533
  • 578
taygetos
  • 3,005
  • 2
  • 21
  • 29