Java: hash function for objects

I am thinking of a hash function for any Java exercise objects. A naive way would be to call the hashCode () function for each attribute, add these hashes, and then take the sum modulo the maximum hash value or something like that. However, this will mean that the hash value will change when attributes change, therefore this method cannot be used if you want to store objects in a hash table. The hash code of the object must represent its identifier. But how can I express this abstract identity as a whole value? Perhaps using the address of the object (suppose Java does not move objects in memory at run time), but is there a way in Java to get the address of objects?

How would you implement such a hash function?

Thanks in advance.

+4
source share
3 answers

java.lang.System has an identityHashCode(Object) method that returns a value that does not change for the life of the object. It can be connected (in some mystical, implementation-dependent manner) with the address of the machine object. Anyway, that’s why this method exists.

+2
source

I think the Effective Java chapter on methods common to all objects is a great resource here.

+4
source

This would not be a suitable hash function. Remember that hashCode must return the same value if two objects are equal (according to the equality method). Therefore, using the memory address of an object will not meet these criteria.

Check out the hashCode contract. http://download.oracle.com/javase/6/docs/api/java/lang/Object.html#hashCode ()

+2
source

All Articles