Java:对象的散列函数 [英] Java: Hash function for objects

查看:120
本文介绍了Java:对象的散列函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑用于练习手段的任意Java对象的散列函数。天真的方法是调用每个属性的hashCode()函数,添加这些哈希值,然后以总和为模最大哈希值或类似的东西。但是,这意味着,只要属性发生更改,散列值就会更改,因此如果要将对象存储在散列表中,则无法使用此方法。对象的哈希码应该代表其身份。但是,我怎样才能将这个抽象的身份表达为一个整数值呢?也许通过使用对象地址(假设Java在运行时不会移动内存中的对象),但在Java中有没有办法获得对象地址?

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.

推荐答案

java.lang.System 有一个方法 identityHashCode(Object),它返回一个不会改变的值为了一个物体的生命。它可能与对象的机器地址有关(以某种神秘的,依赖于实现的方式)。无论如何,这就是为什么那个方法在那里。

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.

这篇关于Java:对象的散列函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆