Is there a way to get a unique Java hash code from objects like HashMap?


I believe that if I declare a HashMap and repeatedly feed it instances of Map.Entry eventually a hashcode will collide with another hashcode even if the two keys (which happen to be Strings for my needs) are different.

At that point HashMap and other classes that use hashing will produce a different hash code which serves as the real key for internal use. (Edit: this turned out to be not true. Please see the selected answer.)

Is there a way to get that internal key? The reason I want it is because a 32 bit key is more efficient memory and speed-wise than the real world key which would be a (possibly) longish string.

I can make a hash code registry for my Strings but why bother if Java already can do this.

No. You can't get a unique 32 bit number for every possible object in your system.

The simplest proof for this is that on a 64bit JVM with sufficient amounts of memory you can easily have more than 2^32 objects: thus you'd need more than 2^32 different hash values. But since you only have 32 bits to store those hash values, you can't get more than 2^32 different hash values. This is called the Pidgeonhole principle.

Also: HashMap doesn't produce a "unique hash code": it simply stores all elements with the same hash code in the same bucket (in a linked list) and checks every one of them using equals() if it has to retrieve one of those.