我理解 hashCode 的想法以及为什么需要它。但是我对如何计算通用对象的 hashCode 感到困惑。这是我的问题。如果我有一个字符串,我可能会使用以下函数来计算 hashCode,
int hash = 7;
for (int i = 0; i < strlen; i++) {
hash = hash*31 + charAt(i);
}
但假设我有以下对象,
class Node<K, V> {
private K key;
private V value;
private Node<K, V> next;
}
我的 IDE 为此生成一个自动 hashCode 函数,
@Override
public int hashCode() {
int result = key != null ? key.hashCode() : 0;
result = 31 * result + (value != null ? value.hashCode() : 0);
result = 31 * result + (next != null ? next.hashCode() : 0);
return result;
}
我的问题是,既然 Key 和 Value 是通用的,那么 key.hashCode()
是做什么的?
这个方法是如何工作的?
最佳答案
K
和V
是你的 Node
的参数化类型目的。
因此,hashCode
将在实际类型上调用。
例如Node<String, Integer>
将有String#hashCode
和Integer#hashCode
分别调用。
如果您使用自定义对象对其进行参数化,则可以使用它们自己的 hashCode
实现或其 parent 的 hashCode
的实现将被调用,最多Object#hashCode
,这是一个 native (即依赖于平台)实现。
关于java - Java 中通用对象的 HashCode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38596132/