Why the following three strings's hashcode are same?

  • A+
Category:Languages

After reading the source code of JDK, I am still surprised that the strings "AaAa", "AaBB" and "BBBB" have the same hashcode.

The source of JDK is as follows,

int h = hash; if (h == 0 && value.length > 0) {     char val[] = value;      for (int i = 0; i < value.length; i++) {         h = 31 * h + val[i];     }     hash = h; } return h; 

Anyone could clarify this?

 


Because that's how the hash code is defined to be calculated for a String:

The hash code for a String object is computed as

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] 

So:

  • For AaAa: 65*31^3 + 97*31^2 + 65*31 + 97 = 2031744
  • For AaBB: 65*31^3 + 97*31^2 + 66*31 + 66 = 2031744
  • For BBBB: 66*31^3 + 66*31^2 + 66*31 + 66 = 2031744

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: