- hashcode相等值不一定相等炸茧,值相等hashcode一定相等
- String的hashcode方法重寫了
public static int hashCode(byte[] value) {
int h = 0;
for (byte v : value) {
h = 31 * h + (v & 0xff);
}
return h;
}
- 由于哈希碼(HashCode)的目的是為了區(qū)分對(duì)象,所以其分布自然是越均勻越好。為了保證分布均勻痴奏,一般的方法是使用一些相對(duì)大的素質(zhì)冰蘑,但是為什么選擇了31,而不是 23评汰、29纷捞、37 或者直接更大的,如97?
- hashcode的6種生成策略 https://zhuanlan.zhihu.com/p/348612455
可以通過在JVM啟動(dòng)參數(shù)中添加-XX:hashCode=4被去,改變默認(rèn)的hashCode計(jì)算方式主儡。
hashCode=0
if (hashCode == 0) {
value = os::random() ;
}
此類方案返回一個(gè)Park-Miller偽隨機(jī)數(shù)生成器生成的隨機(jī)數(shù)OpenJdk 6 &7的默認(rèn)實(shí)現(xiàn)。
- hashCode=1
if (hashCode == 1) {
intptr_t addrBits = cast_from_oop<intptr_t>(obj) >> 3 ;
value = addrBits ^ (addrBits >> 5) ^ GVars.stwRandom ;
}
此類方案將對(duì)象的內(nèi)存地址惨缆,做移位運(yùn)算后與一個(gè)隨機(jī)數(shù)進(jìn)行異或得到結(jié)果糜值。
- hashCode = 2
if (hashCode == 2) {
value = 1 ; // for sensitivity testing
}
此類方案返回固定的1。
- hashCode = 3
if (hashCode == 3) {
value = ++GVars.hcSequence ;
}
此類方案返回一個(gè)自增序列的當(dāng)前值坯墨。
- hashCode = 4
if (hashCode == 4) {
value = cast_from_oop<intptr_t>(obj) ;
}
此類方案返回當(dāng)前對(duì)象的內(nèi)存地址寂汇。
- hashCode 為 其它
通過和當(dāng)前線程有關(guān)的一個(gè)隨機(jī)數(shù)+三個(gè)確定值,運(yùn)用Marsaglia's xorshift scheme隨機(jī)數(shù)算法得到的一個(gè)隨機(jī)數(shù)捣染。JDK8 的默認(rèn)hashCode的計(jì)算方法就是這個(gè)xorshift 算法骄瓣。