HashMap functions get vs put
Hi!
I recently created a programme where I used a HashMap for storing a large number of (key, value) pairs. I needed to check if an entry was present and if not, add the entry and if so, change the value of the entry.
In the code below, CoOccurrence is an object storing a key and value pair.
I first tried with:
Code:
public void updateHashMap(CoOccurrence co) {
CoOccurrence temp = this.get(co.getKey());
if( temp != null ){
temp.increaseValueByOne();
}
else{
this.put(co.getKey(),co.getValue());
}
}
This way of going about made my programme run for hours, actually up to 12 hours. Then I decided to try the following:
Code:
public void updateHashMap(CoOccurrence co) {
CoOccurrence temp = this.put(co.getKey(), co.getValue());
if( temp != null ){
temp.increaseValueByOne();
this.put(co.getKey(), temp.getValue());
}
}
and this only took seconds to execute.
Anyone with a guess as to why it behaved like this? Is the put-operation faster than the get?
-tahni.