Java:最简单的整数哈希

标签 java hash

我需要一个快速的整数散列函数:

 int hash(int n) { return ...; }

Java 中是否已经存在一些东西?

我需要的最少属性是:

  • hash(n) & 1 在与一堆连续的 n 值一起使用时不会出现周期性。
  • hash(n) & 1 为 0 或 1 的可能性大致相等。

最佳答案

HashMap,以及Guava的基于hash的utilities , 在 hashCode() 结果上使用以下方法来改善位分布并防御较弱的哈希函数:

  /*
   * This method was written by Doug Lea with assistance from members of JCP
   * JSR-166 Expert Group and released to the public domain, as explained at
   * http://creativecommons.org/licenses/publicdomain
   * 
   * As of 2010/06/11, this method is identical to the (package private) hash
   * method in OpenJDK 7's java.util.HashMap class.
   */
  static int smear(int hashCode) {
    hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12);
    return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4);
  }

关于Java:最简单的整数哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9624963/

相关文章:

javascript - 使用多个对象作为键的哈希/关联数组

c# - 创建用于数据库的哈希码(即不使用 GetHashCode)

javascript - Java 8 Lambdas 与 JavaScript 中的自执行函数

java - 我需要为 JDK 1.9 下载哪个 Jersey 版本?

javascript - 将 OAuth id token 从 html 页面传递到 servlet

java - 如何编写一个接受泛型参数的方法?

Java xml 自闭标签

c++ - 将值添加到单独链接的哈希表 C++

Python unhash 值

data-structures - 稀疏哈希表的主要实现思想是什么?