Usually the code hash is used with key for scattering tables, the so-called dictionaries. It is common for the maximum possible code value to be stored in 32 bits, so it makes sense to use the maximum multiple of 32 and the immediate lower prime is 31. Not that you need to use all the codes, but from that number you can derive the most appropriate index according to the amount of Buckets possible in that specific scattering thus giving a good distribution.
According to comments, today it is considered that there are better numbers (larger), but as far as I know the reason for the initial choice was this. A smaller number could generate code collisions much more easily. A bigger one is really better, but the gain difference is not so big, already a smaller one is much worse.
On some platforms an operation of shift of certain numbers is cheap, in others is not, in some cases there is optimization for some numbers, as is the case of the 31 that can be used (is a shift and a simple subtraction).
You could say it’s not a well-thought-out number, there was no deep evaluation, something that has a sensational justification :)
A comparison was made on Soen. It seems that certain numbers give in the same, but note that other observations need to be made, one cannot take the analysis in isolation. Ali shows no other problems of each number.
A few years ago, I have seen criticism regarding the choice of this number, which claim to have been a bad choice. I will try to look for the link.
– Victor Stafusa
@Victorstafusa Included the question link in Soen. Indeed a another question linked there says that Java used for unnecessary performance reasons today and suggests larger numbers for future implementations of
hashCode()
.– Piovezan
https://dzone.com/articles/what-is-wrong-with-hashcode-in-javalangstring
– Victor Stafusa
There are criticisms of the article in the respective comments. You have to digest their content well to conclude something. Criticize the claim that using strings as keys in Hashmaps leaves the application subject to Dos attacks.
– Piovezan