First look at the implementation of the Hashcode method in string
1 Public inthashcode () {2 inth =Hash;3 if(h = = 0 && value.length > 0) {4 CharVal[] =value;5 6 for(inti = 0; i < value.length; i++) {7H = * H +Val[i];8 }9hash =h;Ten } One returnh; A}
In the string class, there is a private instance field hash representing the hash value of the string, the hash value of the strings is computed and assigned to the hash field the first time the Hashcode method is called, and then the Hashcode method can be called directly to return the hash field.
The Hashcode calculation method in the string class is relatively simple, that is, 31 is the right, each character is the ASCII value of the operation, with natural overflow of the equivalent modulo.
The hash calculation formula can be counted 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
Mainly because 31 is a singular prime number, so 31*i=32*i-i= (i<<5)-I, this displacement and subtraction in combination with the calculation of a lot faster than the general operation.
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, which is often difficult to do unless there is guaranteed no hash conflict.
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 strings are equal or string palindrome, and there are counter examples.
About the Hashcode method of the string class in Java