我需要制作HashMap<Integer, List<MySpecialClass> >
的副本,但是当我更改副本中的某些内容时,我希望原始图片保持不变。即当我从副本的List<MySpecialClass>
中删除某些内容时,它会保留在原始的List<MySpecialClass>
中。
如果我正确理解,这两种方法只会创建浅拷贝,这不是我想要的:
mapCopy = new HashMap<>(originalMap);
mapCopy = (HashMap) originalMap.clone();
我对吗?
除了遍历所有键和所有列表项并手动复制之外,还有更好的方法吗?
最佳答案
没错,浅拷贝不能满足您的要求。它将具有原始 map 中List
的副本,但是这些List
会引用相同的List
对象,因此一个List
对HashMap
的修改将出现在另一List
的相应HashMap
中。
在Java中,没有为HashMap
提供深层复制,因此您仍然必须循环浏览所有条目,并在新的put
中对它们进行HashMap
编码。但是您也应该每次也复制List
。像这样:
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
对象,并且所做的更改未反射(reflect)在复制的List
的HashMap
中,那么您也需要为其进行新的复制。关于java - 如何在Java中复制HashMap(不是浅拷贝),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28288546/