Why two objects with the same hashcode are not necessarily equals? [duplicate]

拥有回忆 提交于 2019-12-16 18:05:22

问题


Currently I drilled into the JSE source code for fun. From some tutorials I found a principle two equals objects (i.e. as to object a and b a.equals(b) returns true) must have the same hashcode, on the other hand, two objects with the same hashcode are not necessarily equals. According to the HashTable source code of Java API (http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Hashtable.java), e.g. refer to line 254, we can almost derive equals => same hashcode, but I still can not fully understand why two objects with the same hashcode are not necessarily equals. Anyone can give more reasoning on this? Thanks in advance

Note! This question is more interested in why two objects with the same hash code are not necessarily equals


回答1:


That's a simple matter of counting. A hash code is an integer so has 32 bits. Take now a Long for example. Since it is 64 bits long, there are much more values than 232. Hence there must be a lot of values having the same hash code.



来源:https://stackoverflow.com/questions/40004359/why-two-objects-with-the-same-hashcode-are-not-necessarily-equals

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