Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Hash function for objects

Tags:

java

hash

I'm thinking about a hash function for arbitrary Java-objects for exercise means. The naive way would be to call the hashCode()-function for each attribute, add these hashes and then take the sum modulo the maximal hash value, or something like that. However, that would mean, that the hash value would change whenever on of the attributes is changed, so this method cannot be used if you want to store objects in a hash table. The hash code of an object should represent its identity. But how can I express this abstract identity as an integer value? Maybe by using the object address (supposing, Java doesn't move objects in the memory during runtime), but is there a way in Java to get an objects address?

How would you implement such a hash function?

Thanks in advance.

like image 223
j0ker Avatar asked Sep 14 '11 21:09

j0ker


2 Answers

I think Effective Java's chapter about methods common to all objects is a great resource here.

like image 165
Johannes Weiss Avatar answered Sep 20 '22 12:09

Johannes Weiss


java.lang.System has a method identityHashCode(Object) which returns a value that doesn't change for the life of an object. It may be related (in some mystical, implementation-dependent way) to the object's machine address. Anyway, this is why that method is there.

like image 25
Ernest Friedman-Hill Avatar answered Sep 19 '22 12:09

Ernest Friedman-Hill