that the hash code for a given key is calculated in detail using this formula
In the case, Stringthis is calculated using String#hashCode();, which is implemented as follows:
public int hashCode() {
int h = hash;
int len = count;
if (h == 0 && len > 0) {
int off = offset;
char val[] = value;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
}
return h;
}
Mostly following the equation in java doc
hashcode = s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
It is interesting to note that it Stringactually caches its hash code. He can do this because he Stringis immutable.
If I compute the String"Amit" hash code , it will match this integer:
System.out.println("Amit".hashCode());
> 2044535
, , .
Java HashMap , 2 ^ n . , , 16, , , 2 ^ 4.
put , - . - , , - ( , ) "" .
, , :
h & (length-1);
, .
"Amit" 10- - -. -twiddeling, 7- , 2044535 & 15 = 7.
, , . , , .
, .
HashMap - , , ( , 16 * 0,75 = 12), .
Resize 2 * , , , , .
, .
, , , , HashMap , .