Java: Hash function for objects

痴心易碎 提交于 2019-12-23 10:09:30

问题


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.


回答1:


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.




回答2:


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




回答3:


That would not be an appropriate hash function. Remember that hashCode should return the same value if two objects are equal (according the to the equal method). Therefore, using the memory address of the object would not satisfy this criteria.

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



来源:https://stackoverflow.com/questions/7422998/java-hash-function-for-objects

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!