Thursday, July 27, 2006

Is HashCode Unique?

I found in many sites and artilce saying Hashcode is unique. But thats not true always.
just consider this example. As u know HashCode is int32, that means at a given point of time u can have max 2^32 different values. At that point of time u can have more than 2^32 different objects. That means hashcode must be duplicated.

There is another claim saying at least for string objects hascode is unique, that is also not true, the reason is. As we have 26 alphabets total no of differe string u can have is 26!(26 factorial) (I am just considering 26 char length single word only), which is bigger number than 2^32. That means two different string can have same hashcode is it not!.
Based on the above discussion we can say Hashcode is not unique.

*Please not that this is just my understanding, Correct me if i am wrong.

5 comments:

Anonymous said...

A very nice explanation on Hash Code.

Anonymous said...

Your findings are logical.

But hashcode is generally used by collections like hashtable to find the objects with key object's hashcode. 2 ^32 -1 is practically a very big number. No real collection will have that many elements. So generally it doesn't create any problems.

I would like to have an explanation of atleast one hashing algorithm, the internal management of hashcode in collections like hashtable and the problems associated in general with hashing algorithms.

Elena, Jaco, Anna Maria i Teo said...

I actually encounter a problem in development where two differnt strings produced the same hashcode, so the probability is not small.

Collections use the hashcode to put items in different bins allowing for the possibility of two items in a bin.

Bernardo Breder said...

I want to know, if hashcode with the same size of string can be unique?

Bernardo Breder said...

Please, i need this