<分区>
看了JDK的源码,觉得HashMap的hash()
函数很好玩。它的源代码是这样的:
static int hash(int h) {
// This function ensures that hashCodes that differ only by
// constant multiples at each bit position have a bounded
// number of collisions (approximately 8 at default load factor).
h ^= (h >>> 20) ^ (h >>> 12);
return h ^ (h >>> 7) ^ (h >>> 4);
}
参数h
是来自Objects
的hashCode 被放入HashMap
。这种方法是如何工作的,为什么?为什么这种方法可以防御较差的hashCode函数?