我试图计算字符串中每个字符的出现次数(仅包含小写字母)。我建立了一个HashMap,所有字符都初始化为0。更新时,遇到错误。
代码是:
private static HashMap<Character, Integer> addToMap(String s) {
HashMap dict = new HashMap<Character, Integer>();
for (int i = 0; i < 26; i++) {
dict.put((char)('a' + i), 0);
}
for (int i = 0; i < s.length(); i++) {
dict.put(s.charAt(i), dict.get(s.charAt(i)) + 1);
}
return dict;
}
最佳答案
您错过了想要用于参数化 map 的类型。应该是:
HashMap<Character, Integer> dict = new HashMap<>();
关于Java错误: bad operand types for binary operator in HashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49061343/