在 Java 中复制 HashMap [英] Copying a HashMap in Java
问题描述
我正在尝试保留一个包含成员的类的临时容器:
I am trying to keep a temporary container of a class that contains member :
HashMap<Integer,myObject> myobjectHashMap
一个名为 myobjectsList 的类
A class called myobjectsList
那我做
myobjectsListA = new myobjectsList();
myobjectsListB = new myobjectsList();
然后:将一些 hashmap 项添加到 A(如 2)
then: Add some hashmap items to A (like 2)
然后:
myobjectListB = myobjectListA; //B has 2
然后:将 hashmap 项添加到 A(比如另外 4 个)
then: Add hashmap items to A (like 4 more)
然后:将A返回到B中存储的项目
then: return A to the items stored in B
myobjectListA = myobjectListb;
但是当我这样做时,当我向 A 添加哈希图项时,B 会随着 A 增长.A 现在有 6 个项目,因为 B 有 6 个.
But when I do this, B grows with A while I am adding hashmap items to A. A now has 6 items in it because B had 6.
我希望 A 在最后一次分配后仍然保留原来的 2.在 C++ 中我会使用对象的复制,java 的等价物是什么?
I want A to still have the original 2 at the end after last assignment. In C++ I would use copy with objects, what is the java equivalent?
补充:好的,我遗漏了一些东西来解释这一点.MyObjectsList
不包含 HashMap,它派生自具有 HashMap 成员的类 MyBaseOjbectsList
并且 MyObjectsList
扩展了 MyBaseOjbectsList
.这有什么不同吗?
Added: OK I left something out explaining this. MyObjectsList
does not contain the HashMap, it is derived from a class MyBaseOjbectsList
which has the HashMap member and MyObjectsList
extends MyBaseOjbectsList
. Does this make a difference?
推荐答案
如果你想要一个 HashMap 的副本,你需要构造一个新的.
If you want a copy of the HashMap you need to construct a new one with.
myobjectListB = new HashMap<Integer,myObject>(myobjectListA);
这将创建地图的(浅)副本.
This will create a (shallow) copy of the map.
这篇关于在 Java 中复制 HashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!