Java hashcodes collide in one case and not the other for the same objects, why? (Code Below)

纵然是瞬间 提交于 2019-12-06 07:29:20

Matt Timmermans' answer covers the basic issues fairly well, particularly "You can't expect to have any consistency...between different runs." (+1)

The default Object.hashCode() implementation (also called the identity hash code because it's the same as System.identityHashCode(obj)) is currently, in Hotspot, just a pseudo-random number with a thread-local seed. There hasn't been any dependency on the object's memory address for quite some time. If your program execution is completely deterministic, the hashes will most likely be repeatable.

Also note that the identity hashcode is lazily generated on the first call to Object.hashCode() or System.identityHashCode() and the value is stored in the object so that subsequent calls on this object will return the same value. If you run your collision detector loop in another thread, you'll get completely different hash values, and thus different collisions.

When you don't override hashCode(), you get the identity hash code function inherited from class Object.

The identity hash code depends on stuff you can't see that can theoretically change every time you run your program, like where the object ends up in memory, the number of objects created before yours, etc. You just can't expect to have any consistency in identity hash values between different runs of your program or method.

However, if you run exactly the same program twice, and it's not too big, the odds are pretty good that you will end up with the same hashes both times. If you change the program, though, you change how much memory will be consumed by loading and compiling the class, which is very likely to change the identity hashes by changing the location in memory that your objects will go to.

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