哈希表不递减

Hashtable not decrementing

哈希表的值在第二次循环中没有递减 1 maga_split array.They 与第一次循环中的值保持相同。

Hashtable<String,Integer> notemap=new Hashtable<String,Integer>();
String[] note_split={give,one,grand,today};
String[] maga_split={give,me,one,grand,today,night};
for(int i=0;i<note_split.length;i++)
        {
            if(!notemap.contains(note_split[i]))
            {
                notemap.put(note_split[i],1);
            }
            else
            {
                notemap.put(note_split[i],notemap.get(note_split[i])+1);
            }
        }


        for(int i=0;i<maga_split.length;i++)
        {
            String s=maga_split[i];
            if(!notemap.contains(s))
            {
                notemap.put(s,1);
            }
            else
            {
                notemap.put(s,notemap.get(s)-1);
            }
        }

        for(Map.Entry s:notemap.entrySet())
        {
            System.out.println(s.getKey()+"="+s.getValue());        }

您的代码无法运行,因为您正在使用 notemap.contains()。如果您阅读 contains() 的文档:

Tests if some key maps into the specified value in this hashtable. This operation is more expensive than the containsKey method. Note that this method is identical in functionality to containsValue, (which is part of the Map interface in the collections framework).

所以您不是在测试键是否在 table 中,而是在测试值。 使用地图时,最好 在可能的情况下使用 Map 界面 : Map<String, Integer> notemap = new HashMap<>();。这样你就可以确定你正在为地图调用标准接口,并且你可以根据需要切换地图的实现,例如从 HashMap 到 TreeMap。 那么你应该使用containsKey()方法