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(不是浅拷贝)


基础教程推荐
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 降序排序:Java Map 2022-01-01