【发布时间】:2012-06-22 06:05:50
【问题描述】:
这是来自 Java HashTable 类的 hashCode() 实现。如果哈希表中的元素数量很大并且哈希码超过 INTEGER MAX LIMIT -2,147,483,648 到 2,147,483,647 怎么办?我假设 hashCodes 将是正整数。
public synchronized int hashCode() {
int h = 0;
if (count == 0 || loadFactor < 0)
return h; // Returns zero
loadFactor = -loadFactor; // Mark hashCode computation in progress
Entry[] tab = table;
for (int i = 0; i < tab.length; i++)
for (Entry e = tab[i]; e != null; e = e.next)
h += e.key.hashCode() ^ e.value.hashCode();
loadFactor = -loadFactor; // Mark hashCode computation complete
return h;
}
【问题讨论】:
-
超过int类型(32位)限制的位将被丢弃。
-
“如果哈希表中的元素数量很大怎么办”?怎么样 - 哈希表必须处理冲突。没有要求也没有保证哈希码是唯一的(确实,不可能有这样的保证)
-
System.out.println("Are hashCodes always positive?".hashCode());打印-835520151;)
标签: java hash integer hashmap hashtable