我遇到了这个问题:我要编写一个方法 contains3,它接受一个字符串列表作为参数,如果任何单个字符串在列表中至少出现 3 次,则返回 true,否则返回 false。我需要使用地图。
当一个词出现三个实例时,仍然不返回true;我很难找到出错的地方。
这是我所拥有的:
private static boolean contains3(List<String> thing) {
Map<String, Integer> wordCount = new TreeMap<String, Integer>();
for (String s: thing) {
String word = s;
if (wordCount.containsKey(word)) { // seen before.
int count = wordCount.get(word);
wordCount.put(word, count + 1);
} else {
wordCount.put(word, 1); // never seen before.
}
if (wordCount.containsValue(3)) {
return true;
} else {
return false;
}
}
return false;
}