我需要一个快速的整数散列函数:
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/