java - 在清除内容后尝试将 Hashmap 的内容插入另一个 hashmap 时会产生问题
问题描述
我有三个哈希图
HashMap<Character, Integer> hm1 = new HashMap<Character, Integer>();
HashMap<Character, Integer> hm_temp = new HashMap<Character, Integer>();
HashMap<String, HashMap<Character, Integer>> hm2 = new HashMap<String, HashMap<Character, Integer>>();
在我将 hm1 的内容插入 hm_temp 然后将 hm_temp 内容插入 hm2 之后
hm_temp.putAll(hm1);
hm2.put(s, hm_temp);
然后我在将新数据插入 hm1 之前清除 hm1 的内容
hm1.clear();
但问题是当我清除 hm1 时,它也在清除 hm2 中的 hash_temp 数据。有人可以详细说明这里的根本问题是什么。
public class Groupduplicates {
public static void main(String[] args) {
String[] strArray = {"crazy", "zacry", "means"};
HashMap<Character, Integer> hm1 = new HashMap<Character, Integer>();
HashMap<Character, Integer> hm_temp = new HashMap<Character, Integer>();
HashMap<String, HashMap<Character, Integer>> hm2 = new HashMap<String, HashMap<Character, Integer>>();
int arrLen = strArray.length;
for(String s: strArray)
{
System.out.println(hm1);
char[] y = s.toCharArray();
for(Character ch: y)
{
if(hm1.containsKey(ch))
hm1.put(ch, hm1.get(ch)+1);
else
hm1.put(ch, 1);
}
System.out.println(hm1);
hm_temp.putAll(hm1);
System.out.println(hm_temp);
hm2.put(s, hm_temp);
System.out.println(hm2);
hm1.clear();
}
System.out.println(hm2);
}
}
解决方案
我认为您想Map<Character, Integer> hm_temp = new HashMap<>();
在循环内执行操作,因此每个单词都有一个全新的 hm_temp:
Map<Character, Integer> hm_temp = new HashMap<>();
hm_temp.putAll(hm1);
甚至
Map<Character, Integer> hm_temp = new HashMap<>(hm1);
完整代码:
String[] strArray = {"crazy", "zacry", "means", "papa"};
Map<Character, Integer> hm1 = new HashMap<>();
Map<String, Map<Character, Integer>> hm2 = new HashMap<>();
for(String s: strArray) {
char[] y = s.toCharArray();
for(Character ch: y) {
if(hm1.containsKey(ch)) {
hm1.put(ch, hm1.get(ch) + 1);
} else {
hm1.put(ch, 1);
}
}
Map<Character, Integer> hmTemp = new HashMap<>(hm1);
hm2.put(s, hmTemp);
hm1.clear();
}
System.out.println(hm2);
这输出:
{means={a=1, s=1, e=1, m=1, n=1}, papa={p=2, a=2}, zacry={a=1, y=1, r= 1, z=1, c=1}, 疯狂={a=1, y=1, r=1, z=1, c=1}}
笔记:
此外,在声明您的地图时,请使用该Map
界面。您也不需要重复泛型,即:
Map<Character, Integer> hm1 = new HashMap<>();
Map<String, Map<Character, Integer>> hm2 = new HashMap<>();
而且你应该使用驼峰式大小写,而不是下划线,所以hmTemp
推荐阅读
- firebase - 我如何将firebase输出更改为具有本机反应的文本,从我现在所拥有的
- javascript - 为什么 React 会丢弃整个 DOM 子树并从头开始重新创建它?
- python - 尝试从日期开始按月拆分/排序文件
- python - 替换列表中的索引字符串并写入文本文件
- javascript - 从通知图标中删除号码
- java - 将 java 类路径设置为具有 jar 文件并从命令行运行的多个文件夹
- node.js - 不可能将用户导入firebase,散列问题
- tensorflow - 错误:无法使用给定的会话来评估张量:张量的图表与会话的图表不同
- html - 表格、行、单元格内的边框或表格?
- css - 如果“用户”已登录,我想每次都调用自动检查。如果没有,则“用户”登录,然后重定向回(url)