【问题标题】:calculating frequency of an element in hashmap计算哈希图中元素的频率
【发布时间】:2017-09-14 23:22:19
【问题描述】:

我正在使用 hashmap 实现一个包,我正在尝试计算我的 hashmap 中一个元素的频率,但我一直比它应该的少一个。

这是我的地图

  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 实现的新手

【问题讨论】:

  • 地图中的值代表什么?
  • 我不知道你为什么要返回 k 而不是 freq 中的 numE?我误解了你的问题吗?在您的测试中,地图将是 {4 : 1, 5 : 2}。如果您正在寻找“2”,map.get(5) 会返回它。

标签: java hashmap bag


【解决方案1】:

好的,如果我理解您的问题,您需要地图中某个元素的值。因此,如果您的地图是 {4 : 1, 5 : 2},freq(5) 应该是 2,freq(4) 应该是 1。我不确定您为什么使用 Collections.frequency,请查看文档,该方法返回集合中的值的数量。因此,对于地图中的任何键,它将返回 1,因为地图不能包含重复的键。你需要的是这样的:

public int freq(int element) {
    return map.get(element);
}

【讨论】:

    猜你喜欢
    • 2020-03-20
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-07
    • 2021-07-28
    • 1970-01-01
    相关资源
    最近更新 更多