java - 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?
解决方案
要进行克隆,您必须使用HashMap
构造函数HashMap(Map m)
Map<String,Integer> GeneMapClone = new HashMap<>(GeneMap);
因为当前GeneMap
和GeneMapClone
都指向堆内存中的同一个对象
推荐阅读
- aws-lambda - AWS Lambda 中使用 RollupJS 的 Node-sass 错误
- android - 如何将 Unity 游戏推送到我的 Android Studio 应用程序中?
- sql - 如何在sql server的表中只查找日文名称和英文名称数据
- go - 无法在 Linux 中安装任何 GoLang 脚本
- javascript - 我如何用玩笑监视第三方功能?
- javascript - Javascript Promise 链接下来不执行 then()
- java - Solr 内容搜索在文档更新后停止工作
- python - 如何使用python在具有指定模式的特定级别的子目录中查找具有给定扩展名的文件?
- resttemplate - Exchange RestTemplate 给出 400 Bad Request
- php - JSON API 因变量中的“(双引号)而失败