How to copy HashMap (not shallow copy) in Java

后端 未结 5 957
情书的邮戳
情书的邮戳 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 05:03

    You're right that a shallow copy won't meet your requirements. It will have copies of the Lists from your original map, but those Lists will refer to the same List objects, so that a modification to a List from one HashMap will appear in the corresponding List from the other HashMap.

    There is no deep copying supplied for a HashMap in Java, so you will still have to loop through all of the entries and put them in the new HashMap. But you should also make a copy of the List each time also. Something like this:

    public static HashMap> copy(
        HashMap> original)
    {
        HashMap> copy = new HashMap>();
        for (Map.Entry> entry : original.entrySet())
        {
            copy.put(entry.getKey(),
               // Or whatever List implementation you'd like here.
               new ArrayList(entry.getValue()));
        }
        return copy;
    }
    

    If you want to modify your individual MySpecialClass objects, and have the changes not be reflected in the Lists of your copied HashMap, then you will need to make new copies of them too.

提交回复
热议问题