问题描述
根据 ,HashMap在已经检索到的哈希码上重新调用自己的 hashCode()
实现(称为 hash()
)。 / b>
准确地可以重新分配哈希码吗? HashMap可以存储对象,但它无法访问为其对象分配hashCode的逻辑。例如, hash()
不可能将逻辑整合到下面的 hashCode()
实现中:
public class Employee {
protected long employeeId;
保护字符串firstName;
保护字符串lastName;
public int hashCode(){
return(int)employeeId;
}
}
hash()
从实际的哈希码派生出改进的哈希码,所以相同的输入总是等于输出(来自jdk1.8.0_51):
static final hash(Object key){
int h;
return(key == null)? 0:(h = key.hashCode())^(h>>> 16);至于为什么哈希码需要改进,请阅读该方法的javadoc:
$ b
According to this blog entry, HashMap reinvokes its own implementation of hashCode()
(called hash()
) on a hashcode it already retrieved.
Can HashMap accurately reassign hashcodes? HashMap can store objects, but it doesn't have access to the logic that assigns a hashCode its objects. For example, hash()
couldn't possibly integrate the logic behind the following hashCode()
implementation:
public class Employee {
protected long employeeId;
protected String firstName;
protected String lastName;
public int hashCode(){
return (int) employeeId;
}
}
The hash()
derives the "improved" hash code from the actual hash code, so equal input will always be equal output (from jdk1.8.0_51):
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}
As to why the hash code needs improvement, read the javadoc of the method:
这篇关于为什么以及如何HashMap有自己的内部实现hashCode()称为哈希()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!