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

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

问题描述

人们能否推荐快速简单的方法来组合两个对象的哈希码.我不太担心冲突,因为我有一个可以有效处理冲突的哈希表,我只想要一些能尽快生成代码的东西.

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. 构建一个字符串,然后使用字符串类的哈希码方法

人们会推荐什么?为什么?

What would people recommend and why?

推荐答案

我个人会避免 XOR - 这意味着任何两个相等的值都会导致 0 - 所以 hash(1, 1) == hash(2, 2)== hash(3, 3) 等.还有 hash(5, 0) == hash(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;
}

这是 Josh Bloch 在 Effective 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.

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

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