首页 > 解决方案 > Map becomes null

问题描述

I am using a Map, cloning it and working with the clone. After the clone has been worked with, the original Map is modified and I don't understand why.

System.out.println("foo = " + GeneMap.get("foo"));
Map<String,Integer> GeneMapClone = GeneMap;
for(int i = 0; i<BestArray.length; i++) {
    for(Map.Entry<String,Integer>entry:GeneMapClone.entrySet()){
        if(BestArray[i] == entry.getValue()) {
            GeneArray[i] = entry.getKey();
            GeneMapClone.remove(entry.getKey());
            break;
        }
    }
}
System.out.println("foo = " + GeneMap.get("foo"));

This will print out the following:

foo = 6
foo = null

By modifying GeneMapClone, am I also modifying GeneMap since it is pointing to it? How can I avoid this?

标签: javadictionarynull

解决方案


要进行克隆,您必须使用HashMap构造函数HashMap(Map m)

 Map<String,Integer> GeneMapClone = new HashMap<>(GeneMap);

因为当前GeneMapGeneMapClone都指向堆内存中的同一个对象


推荐阅读