我应该如何映射长哈希值code为int()? [英] How should I map long to int in hashCode()?
问题描述
我有一个范围,有一个长
,其值唯一标识特定对象在我的整个系统,就像一个GUID字段的对象。我已经重写的Object.Equals()
来使用这个ID进行比较,beause我想这与对象的拷贝工作。现在,我要重写 Object.hash code()
也是如此,这基本上意味着我的映射长
来一些 INT
返回值。
I have a range of objects that have a long
field whose value uniquely identifies a particular object across my entire system, much like a GUID. I have overriden Object.equals()
to use this id for comparison, beause I want it to work with copies of the object. Now I want to override Object.hashCode()
, too, which basically means mapping my long
to some int
return value.
如果我理解散code的目的
正确的,它主要是用在哈希表,所以均匀分布是可取的。这意味着,只返回 ID%2 ^ 32
就足够了。是所有的,或者我应该知道的东西?
If I understood the purpose of hashCode
correctly, it is mainly used in hash tables, so a uniform distribution would be desirable. This would mean, simply returning id % 2^32
would suffice. Is that all, or should I be aware of something else?
推荐答案
如何
Long.valueOf(guid).hashCode();
您可以返回,或者做当您创建的GUID和变量进行缓存。
You could return it, or do it when you create the guid and cache it in a variable.
纵观文档这样做:
(int)(this.longValue()^(this.longValue()>>>32))
这是一个不错的解决方案,因为它利用了Java库 - 总是更好地利用过的东西,已经被测试过
This is a decent solution since it makes use of the Java library - always better to leverage off of something that has been tested already.
这篇关于我应该如何映射长哈希值code为int()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!