如何在Java中复制HashMap(不是浅拷贝) [英] How to copy HashMap (not shallow copy) in Java

查看:1929
本文介绍了如何在Java中复制HashMap(不是浅拷贝)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要复制 HashMap< Integer,List< MySpecialClass> > 但是当我更改副本中的东西时,我希望原稿保持不变。即当我从副本中删除 List< MySpecialClass> 中的某些内容时,它保留在 List 原版的。

I need to make a copy of HashMap<Integer, List<MySpecialClass> > but when I change something in the copy I want the original to stay the same. i.e when I remove something from the List<MySpecialClass> from the copy it stays in the List<MySpecialClass> in the original.

如果我正确理解,这两个方法只创建浅的副本,这不是我想要的:

If I understand it correctly, these two methods create just shallow copy which is not what I want:

mapCopy = new HashMap<>(originalMap);
mapCopy = (HashMap) originalMap.clone();

是吗?

推荐答案

你是一个更好的方法,而不仅仅是遍历所有的键和所有的列表项,一个浅拷贝将不能满足你的要求。它将从您的原始地图中获得 List 的副本,但 List 将指向相同的 List 对象,以便从 HashMap 修改 List 将出现在来自其他 HashMap 的相应列表中。

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.

没有为Java中的 HashMap 提供深度复制,因此您仍然必须遍历所有条目,并且 put 他们在新的 HashMap 。但是你也应该每次都复制 List 。类似这样的:

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<Integer, List<MySpecialClass>> copy(
    HashMap<Integer, List<MySpecialClass>> original)
{
    HashMap<Integer, List<MySpecialClass>> copy = new HashMap<Integer, List<MySpecialClass>>();
    for (Map.Entry<Integer, List<MySpecialClass>> entry : original.entrySet())
    {
        copy.put(entry.getKey(),
           // Or whatever List implementation you'd like here.
           new ArrayList<MySpecialClass>(entry.getValue()));
    }
    return copy;
}



如果您要修改个人 MySpecialClass 对象,并且更改不会反映在您复制的 HashMap List 您还需要制作新的副本。

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.

这篇关于如何在Java中复制HashMap(不是浅拷贝)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆