首页 > 解决方案 > 在清除内容后尝试将 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);
        
        

    }

}

标签: javahashmap

解决方案


我认为您想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


推荐阅读