Hashtable未递减问题:遍历maga_split数组时值未减1
问题排查与修复方案
我来帮你搞定这个问题!你的代码里藏着两个容易踩的小坑,尤其是第一个循环的API误用,直接导致第二个循环的递减逻辑完全达不到预期,咱们一步步拆解:
1. 第一个循环的核心错误:用错了Hashtable的判断方法
你在初始化notemap的时候用了notemap.contains(note_split[i]),但Hashtable的contains()方法是用来检查是否存在某个值**,而不是键**!要判断某个键是否存在,必须用containsKey()方法。
这个错误会让你的notemap初始化彻底跑偏:
- 比如如果
note_split里有重复元素(比如{"give","give"}),第一次put后notemap里是{"give":1},第二次判断contains("give")是在找值等于"give"的条目,显然不存在,所以会再次put{"give":1},而不是把计数加1。 - 从根上就错了的计数,后续第二个循环的递减自然不可能生效。
2. 第二个循环的关键注意点
假设你的第二个循环是想遍历maga_split,遇到notemap里的键就把对应计数减1,那必须注意两点:
- 还是要用
containsKey()判断键是否存在(别再用contains了!) - 减1之后一定要把新值重新put回Hashtable——因为
get()返回的是值的副本,直接修改不会影响Hashtable内部存储的数据。
修正后的完整可运行代码
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++) { String word = note_split[i]; if (!notemap.containsKey(word)) { notemap.put(word, 1); } else { // 取出当前计数加1后重新存入 notemap.put(word, notemap.get(word) + 1); } } // 第二个循环:正确递减匹配到的单词计数 for (int i = 0; i < maga_split.length; i++) { String word = maga_split[i]; if (notemap.containsKey(word)) { int currentCount = notemap.get(word); // 减1后重新存入,确保Hashtable内的值更新 notemap.put(word, currentCount - 1); } } // 打印验证结果,会看到每个匹配的单词计数都减了1 System.out.println(notemap);
额外优化建议(Java 8+)
如果你的项目用的是Java 8及以上版本,可以用getOrDefault()方法简化第一个循环的代码,避免手动判断,可读性和安全性都更高:
for (String word : note_split) { notemap.put(word, notemap.getOrDefault(word, 0) + 1); }
内容的提问来源于stack exchange,提问作者Maximus
相关产品推荐
相关产品推荐

