复制java hashmap [英] copying a java hashmap
问题描述
我试图保留包含成员的类的临时容器:
I am trying to keep a temporary container of a class that contains member :
HashMap<Integer,myObject> myobjectHashMap
一个名为myobjectsList的类
A class called myobjectsList
我做
myojbectsListA = new myojbectsList();
myojbectsListB = new myobjectsList();
然后:将一些hashmap项目添加到A(like2)
then: Add some hashmap items to A (like2)
然后
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;
但是当我这样做时,B随A增长,而我正在向A添加hashmap项。
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 ++中我会使用复制与对象,什么是对等的?
I want A to have original 2 still at end after last assingment in C++ i would use copy with objects, what is the java equivalent?
添加:OK我留了一些东西解释this.MyObjectsList不包含HashMap,它是从类MyBaseOjbectsList派生有HashMap成员和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的副本,你需要构建一个新的。 / p>
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屋!