Why does String's hashCode() use 31 to multiply?

Asked 2 years ago, Updated 2 years ago, 150 views

In Java, the hash code for the String object is s[0]*31n-1 + s[1]*31n-2 + ... + s[n-1] is calculated like this. To illustrate the above equation, s[i] is the ith character in the string, n is the length of the string, and is the index What I'm curious about is why do you use 31 when multiplying? I understand that you have to use a large decimal when multiplying, but why 31 instead of 29, 37, 97?

n-1n-2 is

algorithm string java hash

2022-09-22 22:29

1 Answers

If you look at a book called Effective Java, it explains this part.

" 31 of the formula chosen because it is small. If this value is an even number, the results of the multiplication overflow if the hash value has been lost. Means two is multiplied by the (the drain) bit of movement. Use the minority are some advantages when it is not clear how routinely do so. The good of the 31 can replace the Beat movement and subtraction to multiplication and can improve performance. In other words, 31 * * * * * * * I is like a (I < < 5) - I Of Java, in recent years vm are automatically carries out in this segment optimization. "

Did you explain it?


2022-09-22 22:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.