Home > Article > Web Front-end > Implementation of JAVA-compatible hashCode algorithm code sharing in javascript_Basic knowledge
In Java, a hashCode algorithm can be used to calculate the hash value of a string. Today, a friend suddenly asked me if I can calculate hashCode in js. The calculation result is required to be the same as Java's hashCode calculation.
As for Java’s hashCode, I have never understood its algorithm before, but I guess it shouldn’t be too difficult, so now I wrote this code in Java for testing:
Running result: 899755
Press the Ctrl key and click on the hashCode method name to follow up and take a look at the algorithm. I found that it is a very simple code, as shown below:
for (int i = 0; i < len; i ) {
h = 31*h val[off];
}
hash = h;
}
return h;
}
Okay now, simply transplant it into js and it should be ok. So I wrote the following JS code:
OK, the result is the same as the java calculation. I thought that was done, and then I thought about finding a random string to test:
"Shenyang Shenyang", the running result in JAVA is: 1062711668, but in js it becomes: 26832515444.
I’m so dizzy, there’s something wrong with just trying this! After thinking for a while, I suddenly thought that the length of int in Java seems to be about 2.1 billion, but there is no such limit in js. The problem should be here, so I made a little modification to the previous method:
Test again! OK! You're done. There is no technical content, just a brief summary
Updated on 2013-02-19, the above one is relatively inefficient and will crash when the content is very long. The following code is the optimized code: