HashMap way of doing containsKey not behaving as expected

我怕爱的太早我们不能终老 提交于 2019-12-01 06:11:49

HashMaps find objects by their hash code. Part of the contract is that the key class must override hashCode() as well as equals(). The default hash codes for separate objects aren't equal, so the object isn't found by get. In contrast, when you loop over all entries, the hash code isn't used, so only equals is called, and the object is found.

To find it using get, override hashCode in Coord.

It is always good to override hashCode whenever you override equals, and vice versa.

Hashmap actually works on the principal of hashing. For correct & expected results, the key used in the Hashmap should override equals() as well as hashCode().

So above while you are doing test.containsKey(new Coord(3, 3)) you are creating a new Coord object so its hashcode is different from the Object which you have put it the map, as its callingObject class hasCode() by default. So containsKey() giving a false

But while you are doing a.equals(new Coord(3, 3)) you are calling overriden equals() which is satisfying the conditions you have put in your overridden method, which is being satisfied by both Coord objects, so giving the output as true.

For proper results also override hashCode() correctly.

For more info on how HashMap works in Java, you can see this blog here. Hope this helped.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!