有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java哈希表不递减

哈希表的值在maga_split数组上的秒循环中没有递减1。它们与第一个循环期间保持相同

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());        }

共 (1) 个答案

  1. # 1 楼答案

    您的代码无法工作,因为您正在使用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).

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