How to copy HashMap (not shallow copy) in Java(如何在 Java 中复制 HashMap(不是浅拷贝))
问题描述
我需要复制 HashMap
但是当我更改副本中的某些内容时,我希望原件保持不变.即,当我从副本的 List<MySpecialClass>
中删除某些内容时,它会保留在原始的 List<MySpecialClass>
中.
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();
我说的对吗?
有没有比遍历所有键和所有列表项并手动复制更好的方法?
Is there a better way to do it than just iterate through all the keys and all the list items and copy it manually?
推荐答案
你说得对,浅拷贝不能满足你的要求.它将具有原始地图中 List
的副本,但那些 List
将引用相同的 List
对象,因此修改从一个 HashMap
到一个 List
将出现在另一个 HashMap
的相应 List
中.
You're right that a shallow copy won't meet your requirements. It will have copies of the List
s from your original map, but those List
s 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
到新的 哈希映射
.但是你也应该每次都复制一份 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 List
s of your copied HashMap
, then you will need to make new copies of them too.
这篇关于如何在 Java 中复制 HashMap(不是浅拷贝)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Java 中复制 HashMap(不是浅拷贝)


基础教程推荐
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 修改 void 函数的输入参数,然后读取 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 存储 20 位数字的数据类型 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01