gpt4 book ai didi

java - 复制 HashMap

转载 作者:行者123 更新时间:2023-12-02 07:45:29 24 4
gpt4 key购买 nike

我有一个结构

HashMap<String,HashMap<Integer, HashMap<Integer, question>>> lang=new HashMap<String,HashMap<Integer, HashMap<Integer, question>>>();

HashMap<Integer,HashMap<Integer,question>> section= new HashMap<Integer,HashMap<Integer,question>>();
HashMap<Integer,question> questions= new HashMap<Integer,question>();

根据我的逻辑,我填写问题部分

while(logic){
for(someother logic){

//make the skeleton structure of the object
questions.add(integer,object);
}
section.add(integer,map3);
}

现在我使用这个map2作为骨架并进行更改

HashMap<Integer,HashMap<Integer,object>> tempMap= new HashMap<Integer,HashMap<Integer,object>>();
while(logicnew){
while(logic 2){
tempMap = new HashMap(section);
while(logic 3){
tempMap2 = new HashMap(tempMap.get(integer));
//make my changes
}
}
lang.add(integer,tempMap);
}

多种语言有多个部分,多个部分有多个问题。问题是这些值被过度书写,即如果我有第一语言的法语文本和第二语言的英语文本,我只会在我制作的两个语言映射中看到英语文本。你能告诉我出了什么问题吗?如果有更好的方法请告诉我。

谢谢!

最佳答案

HashMap 是一个通过引用传递的对象(您应该阅读这一点)。

如果您想重用map2,请确保正确克隆map2。否则,您对 map2 所做的修改将反射(reflect)在所有 HashMap 实例中。

在重用map2之前执行此操作:

map2 = (HashMap) map2.clone();

请注意,这是一个浅拷贝。

阅读此处了解更多信息:http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html#clone%28%29

HashMap的深度克隆:

public HashMap deepClone(HashMap map) {
HashMap clone = new HashMap();
Iterator it = map.keySet().iterator();

while (it.hasNext()) {
Object key = it.next();
Object value = map.get(key);
clone.put(key.clone(), value.clone());
}
return clone;
}

这只是一个示例实现,为您提供了一个可以使用的模板。您应该确保 HashMap 是类型安全的,并且键和值具有 Object.clone() 的深度克隆实现

关于java - 复制 HashMap ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10943958/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com