【发布时间】:2010-12-13 23:26:51
【问题描述】:
我们被告知应该为我们的类实现 hashCode(),但是像我这样的大多数人并不真正知道如何执行此操作,也不知道如果我们“错误”了会发生什么。例如,我需要一个哈希函数来索引树中的节点 (Finding the most frequent subtrees in a collection of (parse) trees)。在这种情况下,我需要根据有序的子节点递归生成哈希码,例如
hashCode = function(child1.hashCode, child2.hashCode, ...)
在recent discussion 的 hashCodes 答案中包括字符串的哈希(基于长素数和 31)以及位移。字符串哈希是:
// adapted from String.hashCode()
public static long hash(String string) {
long h = 1125899906842597L; // prime
int len = string.length();
for (int i = 0; i < len; i++) {
h = 31*h + string.charAt(i);
}
return h;
}
我对安全性不感兴趣,也不介意碰撞。有没有一个“通用函数”来组合有序对象的哈希码,它的好处多于坏处(并且比根本不调用它更好)?
还有可以查找常见案例的网站吗?字符串、列表等)
我没有指定一种语言,因为我希望有通用的方法。但如果它是严重特定于语言的,那么请说明语言以及为什么它不是通用的。
更新 两个建议是使用 IDE 的 hashCode 生成器。这似乎是一个极好的默认值。这是 Netbeans:
public int hashCode() {
int hash = 5;
// objects
hash = 97 * hash + (this.rootElement != null ? this.rootElement.hashCode() : 0);
hash = 97 * hash + (this.tableElement != null ? this.tableElement.hashCode() : 0);
// a string
hash = 97 * hash + (this.tag != null ? this.tag.hashCode() : 0);
return hash;
}
【问题讨论】: