current position:Home>Explain the specific calculation of string hashcode in Java

Explain the specific calculation of string hashcode in Java

2022-06-24 09:51:53atwdy

Cut from String Class hashCode Source code of calculation method , among hash The initial value of 0,value The value of is the character array corresponding to the string .
 Insert picture description here  Insert picture description here

The above code is not difficult to understand ,

For empty strings , The length is 0, Do not enter if Conditions , Returns the initial value 0.
For non empty strings , Go through the above... For each character for Cycle is the answer ,for In the loop h = 31 * h + val[i];val[ i ] The value is the character corresponding to unicode code .

About unicode code :https://blog.csdn.net/atwdy/article/details/124714440

Check it out

For strings "abc", Corresponding unicode code :a: 97,b: 98,c: 99
h = 31 x 0 + 97 = 97
h = 31 x 97 + 98 = 3105
h = 31 x 3105 + 99 = 96354

For strings containing Chinese characters " Flying fish a", Corresponding unicode code : fly : 39134, fish : 40060,a: 97
h = 31 x 0 + 39134 = 39134
h = 31 x 39134 + 40060 = 1253214
h = 31 x 1253214 + 97 = 38849731

public class Demo {
    
    public static void main(String[] args) {
    
        System.out.println("abc".hashCode());
        System.out.println(" Flying fish a".hashCode());
    }
}

 Insert picture description here

copyright notice
author[atwdy],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/175/202206240859119482.html

Random recommended