How to copy HashMap (not shallow copy) in Java

后端 未结 5 955
情书的邮戳
情书的邮戳 2020-11-30 04:32

I need to make a copy of HashMap > but when I change something in the copy I want the original to stay the same. i.e w

5条回答
  •  盖世英雄少女心
    2020-11-30 04:57

    You are making a copy of the HashMap itself, so changing the HashMap copy will not change the original HashMap (i.e. adding or removing entries), but because the objects you have stored are not primitive types, the List that you retrieve with a given key will be the same whether retrieved from the first or the second Map.

    Thus, there is still only ONE copy of that list, referenced by both maps: changing the List changes it no matter which reference you use to access it.

    If you want the actual List to be a separate copy, you will have to do as you said: iterate over the entry set of the HashMap and create a copy of each List manually, adding it to the new map as you go.

    If there is a better way than that, I don't know what it is.

提交回复
热议问题