First look at the implementation source of the Hashcode method in string.
Public int hashcode () { int h = hash; if (h = = 0 && value.length > 0) {char val[] = value ; for (int i = 0; i < value.length; i++) { = + * H + val[i]; } = h; } return h;}
There is a private instance field in string that hashes the hash of the string, and when the Hashcode method is called for the first time, the hash value is computed and assigned to the hash field. Then call the Hashcode method to return directly to the hash field.
The Hashcode calculation method in the string class is relatively simple, that is, 131 is the right, each character of the ASCII is only calculated, with natural overflow equivalent modulus.
The hash calculation formula can be recorded as s[0]*31^ (n-1) +s[1]*31^ (n-2) +...+s[n-1].
about why take 31 as the right, you can refer to this problem on the StackOverflow
The main reason is because 31 is a singular prime number, so 31*i=32*i-i= (i<<5)-I, this displacement and shear combined with the calculation of a lot compared to the general operation block.
String hash can do a lot of things, usually similar to a string sentence, such as the sentence palindrome.
But relying solely on hashes to judge is not rigorous, unless it guarantees that there will be no hash conflicts. This is often difficult to do.
Take the hash method of the string class in the JDK for example, the string "Gdejicbegh" with the string "HGEBCIJEDG" has the same hashcode () return value-801038016, and they have a reverse relationship. This example shows that the default Hashcode method in the JDK determines whether the string is equal or the string palindrome has a counter-example.
About the implementation of Hashcode method in Java source code