我正在使用 hashmap 实现一个包,我正在尝试计算 hashmap 中某个元素的频率,但我得到的结果总是比应有的少一个。
这是我的 map
private Map <Integer, Integer> map = new HashMap<>();
这是我的添加方法
public void add(int element) {
//containsKey
//checks if the element is already there
if (map.containsKey(element)){
Integer numElt = map.get(element);
map.put(element, (numElt+1)); //line where it should increment number of keys if the element is already there
count++;
}
else {
map.put(element, 1);
count++;
}
}
和我的频率
public int freq(int element) {
Integer numE = map.get(element);
int k = Collections.frequency(map.values(), numE);
return k;
如果我这样写我的测试
Bag b = new Bag():
b.add(4)
b.add(5)
b.add(5)
assertTrue(2, b.freq(5))
应该返回 2 但它返回 1。不知道为什么会这样,如果这看起来是一个明显的错误,我很抱歉我是 bag 实现的新手
最佳答案
好的,如果我理解您的问题,您需要 map 中某个元素的值。因此,如果您的 map 是 {4 : 1, 5 : 2},则 freq(5) 应为 2,freq(4) 应为 1。我不确定您为什么使用 Collections.frequency,请查看文档,该方法返回集合中值的数量。因此对于映射中的任何键,它将返回 1,因为映射不能包含重复的键。你需要的是:
public int freq(int element) {
return map.get(element);
}
关于java - 计算 HashMap 中元素的频率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43483712/