为什么hashmaps中的不可变对象如此有效? [英] Why are immutable objects in hashmaps so effective?
问题描述
所以我阅读了 HashMap 。有人指出:
不可变性还允许缓存不同密钥的哈希码,这使整个检索过程非常快速,由Java Collection API提供的字符串和各种包装类(例如
Integer
)非常好HashMap
键。 p>
我不太明白...为什么?
String#hashCode
:
private int散列;
...
public int hashCode(){
int h = hash;
if(h == 0& count> 0){
int off = offset;
char val [] = value;
int len = count;
for(int i = 0; i< len; i ++){
h = 31 * h + val [off ++];
}
hash = h;
}
return h;
$ b 由于 String $ c的内容$ c>永远不会改变,这个类的制造者选择在它被计算一次之后缓存哈希值。这样,时间不会浪费,重新计算相同的值。
So I read about HashMap. At one point it was noted:
"Immutability also allows caching the hashcode of different keys which makes the overall retrieval process very fast and suggest that String and various wrapper classes (e.g., Integer
) provided by Java Collection API are very good HashMap
keys."
I don't quite understand... why?
解决方案 String#hashCode
:
private int hash;
...
public int hashCode() {
int h = hash;
if (h == 0 && count > 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
Since the contents of a String
never change, the makers of the class chose to cache the hash after it had been calculated once. This way, time is not wasted recalculating the same value.
这篇关于为什么hashmaps中的不可变对象如此有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!