Reputation: 5466
Here is my code:
double getRevenue(KeywordGroupKey key) {
Double r = revenueMap.get(key);
System.out.println(key + "\t" + key.hashCode());
for (KeywordGroupKey other : revenueMap.keySet()) {
System.out.println(other.toString() + "\t" + other.hashCode());
if(other.equals(key))
System.out.println("equals here...");
}
if(r == null)
r = 0.0;
return r;
}
and here is the output:
优惠打折,优惠券|"优惠券" 955095524
brand+点评团购|大众点评 726983298
brand-品牌词相关|团购网站大全 -713384514
brand-品牌词|点评网 2029153675
brand+点评团购|大众点评网 261410621
优惠打折,优惠券|"优惠券" 955095524
equals here...
So it is so strange that the value returned by the method is null, why dose this happen? Since there is a key in the revenueMap has the same hash code and equals with argument key. Below is the current state of the revenueMap and key:
{brand+点评团购|大众点评=28.0, brand-品牌词相关|团购网站大全=49.9, brand-品牌词|点评网=21.0, brand+点评团购|大众点评网=167.0, 优惠打折,优惠券|"优惠券"=9.9}
优惠打折,优惠券|"优惠券"
Upvotes: 1
Views: 201
Reputation: 308249
My guess is that KeywordGroupKey
is mutable and the key in question was modified after it was used as the key of the hash map.
If that's the case, then the key is in the wrong "bucket" in the HashMap
and the get()
method (or containsKey()
method) will never find it (but iterating over the keys and/or entries will find it!).
For example, assuming there's a property foo
in your class and that property is relevant to your hashCode()
and equals()
methods. The following code would "break" the HashMap
:
KeywordGroupKey key = ...
revenueMap.put(key, someValue);
key.setFoo("differentValue");
Double result = revenueMap.get(key); // will return nothing!
Double result = revenueMap.get(originalValueOfKey); // will *also* return nothing!
Upvotes: 7