Search code examples
javaclonedeep-copyweakhashmap

How to clone/copy WeakHashMap? (Deep copy)


I had a HashMap and I used the clone function to make a deep copy. But I switched this to a WeakHashMap to try out some memory management.

I still want to do this clone function but it isn't part of the methods in WeakHashMap. How do I efficiently clone a WeakHashMap into another one? I suppose I could do a loop, adding keys and checking for existing keys etc, but I'm not sure if that's the best way.


Solution

  • As you have to copy all the elements contained in your map, a for loop is required in order to sequentially visit all key and value pairs.