Reputation: 157
I'm implementing a bag using a hashmap and I'm trying to calculate the frequency of an element in my hashmap and I keep getting one less than what it should be.
this is my map
private Map <Integer, Integer> map = new HashMap<>();
this is my add method
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++;
}
}
and my frequency
public int freq(int element) {
Integer numE = map.get(element);
int k = Collections.frequency(map.values(), numE);
return k;
}
if I write my test like so
Bag b = new Bag():
b.add(4)
b.add(5)
b.add(5)
assertTrue(2, b.freq(5))
should return 2 but it's returning 1. Not sure why that is and I'm sorry if it seems like an obvious error I'm new to bag implementation
Upvotes: 1
Views: 5193
Reputation: 1127
Ok, if I understood your question you want the value of an element in the map. So if you have a map that is {4 : 1, 5 : 2}, freq(5) should be 2 and freq(4) should be 1. I'm not sure why are you using Collections.frequency, check the documentation, that method returns number of values in a collection. So for any key in a map it will return 1, as map cannot contain duplicate keys. What you need is this:
public int freq(int element) {
return map.get(element);
}
Upvotes: 3