快速和简单的哈希code组合 [英] Quick and Simple Hash Code Combinations

查看:149
本文介绍了快速和简单的哈希code组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

人们可以推荐快速和简单的方法来散列codeS结合了两种对象。我不是太担心碰撞,因为我有一个哈希表,它将处理能够有效地我只想要的东西,快速生成一个code越好。

Can people recommend quick and simple ways to combine the hash codes of two objects. I am not too worried about collisions since I have a Hash Table which will handle that efficiently I just want something that generates a code quickly as possible.

阅读周围SO和网络似乎有几个主要候选人:

Reading around SO and the web there seem to be a few main candidates:

  1. 异或
  2. 异或与总理乘
  3. 在简单的数字像乘法/除法运算(带溢出检查或缠绕)
  4. 建立一个String,然后使用String类的哈希code方法

什么人推荐,为什么?

推荐答案

我会亲自避免XOR - 这意味着,任何两个相等的值会导致0 - 所以散列(1,1)==哈希(2,2) ==散列(3,3)等。另外散列(5,0)==散列(0,5)等,这有时可能会出现。我的有无的刻意用它集哈希 - 如果你想哈希项的顺序和你的的关心的排序,这是很好

I would personally avoid XOR - it means that any two equal values will result in 0 - so hash(1, 1) == hash(2, 2) == hash(3, 3) etc. Also hash(5, 0) == hash(0, 5) etc which may come up occasionally. I have deliberately used it for set hashing - if you want to hash a sequence of items and you don't care about the ordering, it's nice.

我通常使用:

unchecked
{
    int hash = 17;
    hash = hash * 31 + firstField.GetHashCode();
    hash = hash * 31 + secondField.GetHashCode();
    return hash;
}

这是乔希布洛赫建议在有效的Java形式。我上次回答了类似的问题,我设法寻找到这个被详细讨论的一篇文章 - IIRC,没有人真正知道为什么它工作得很好,但它确实。这也是易记,易于实施,易于扩展到任意数量的字段。

That's the form that Josh Bloch suggests in Effective Java. Last time I answered a similar question I managed to find an article where this was discussed in detail - IIRC, no-one really knows why it works well, but it does. It's also easy to remember, easy to implement, and easy to extend to any number of fields.

这篇关于快速和简单的哈希code组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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