r/javahelp • u/DelarkArms • Mar 07 '22
HashCodes... Yes... we know... "equal Strings == Equal hashCodes!!1!".
Of course, if 2 strings are equal the hashcode will be the same,
Of course, if you use the hashCode as a persistent ID (for Database or whatever) is a bad idea, but I feel these obviously bad implementations of hashCode muddle every valid implementation the hashCode functionality may have.
What about the innate hashCode of a Java object, No one seems to succinctly address this, do the JVM even keep a registry??
If we need to "care about the hashcode" and "stop using it as an object id", then Why do we even use HashMaps or Sets, do they do something to prevent collisions? , and if they do, why isn't that handled at object instantiation...
By definition if the hashCode() method of an object is as unsafe as it is meant to be, then all those classes should also be unsafe.
Most of the claims of hashCodes being bad as an id, are so vague and allude to the same two examples, that one is left completely unconvinced about it, why would sun make something so untrustworthy?
The only... only believable claim I've seen online, is the one based on the birthday paradox which states that once there are 77 163 objects you have a 50% chance of getting 2 equal hashCodes.
Again, this is a room full of guests, what if within that room you have a bathroom??? What are the chances of getting 2 random people in that bathroom with the same birthday, I bet hashCode is extremely useful on that bathroom alone???
Does this mean that Java becomes completely useless once 77 163 items are created?
Do the JVM even keep a registry of each hashCode created so that it keeps this 50% in check and keeps the chances low??
8
u/philipwhiuk Employed Java Developer Mar 07 '22
What?
The purpose of hashCode is to roughly spread objects equally across a distribution. The fewer the collisions the better.
In the case of a collision a hashSet then stores colliding objects as a list and uses the equality function to check if it’s stored.
A good hashCode function and no collisions results in O(1) search performance. A bad hashCode function where everything has the same hashCode results in O(n) performance.
Yes collisions are inevitable if you have enough objects. The aim is to minimise them.