开发者

Java: HashMap claims it has key, but somehow hasn't

开发者 https://www.devze.com 2023-03-31 19:24 出处:网络
I have a HashMap mapping objects of my Context class to Integers. In the Context class, I did override the public int hashCode() and public boolean equals(Object c) of java.lang.Object. However, I hav

I have a HashMap mapping objects of my Context class to Integers. In the Context class, I did override the public int hashCode() and public boolean equals(Object c) of java.lang.Object. However, I have proble开发者_如何学Pythonms iterating through it:

I want (e.g.) to get the Integer value assigned to each Context object, so I iterate through the key set of the map. But it doesn't work, because the map says it doesn't have the specified key:

for (Context to : map.keySet()) {
    System.out.println("to-hash: " + to.hashCode());
    System.out.println("first-hash: " + map.keySet().iterator().next().hashCode());
    System.out.println("hashs equal: " + (to.hashCode()==map.keySet().iterator().next().hashCode()));
    System.out.println("to equals first: " + to.equals(map.keySet().iterator().next()));
    System.out.println("map has to? " + map.containsKey(to));
}

The output is

to-hash: 156349
first-hash: 156349
hashs equal: true
to equals first: true
map has to? false

From what I understand is that when given a key, the map first checks if the hash codes match, and then checks for equality. Both is the case here, the hash code of the 'to' object and the first object in the key set match and they are also equal. Interestingly, when I change the return value of the hashCode() function to a constant (which is valid, though not recommended for performance reasons), it works. But I don't see why this makes a difference, since 156349==156349 just like 7==7.

I'm quite confused, and I'm afraid that I'm missing something very obvious, and just can't see it. If that's the case, shame on me, but still, I would appreciate a hint :-)

Thanks a lot!


This could happen if your Context object is mutable in a way that affects the hash code, and if you've performed an operation which changes the hash code after putting it in the map. The map will only record the value of hashCode() at the point of insertion and then will use that to find matches when you try to look up a particular key.

This would be consistent with it working if you make the hash function a constant. Basically, you shouldn't mutate hash keys after putting them in a map.

Of course, this is just conjecture, but it does fit the symptoms.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号