Jdk6 source code:
/** * Returns a hash code for this string. The hash code for a * <code>String</code> object is computed as * <blockquote><pre> * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] * </pre></blockquote> * using <code>int</code> arithmetic, where <code>s[i]</code> is the * <i>i</i>th character of the string, <code>n</code> is the length of * the string, and <code>^</code> indicates exponentiation. * (The hash value of the empty string is zero.) * * @return a hash code value for this object. */ public int hashCode() {int h = hash;if (h == 0) { int off = offset; char val[] = value; int len = count; for (int i = 0; i < len; i++) { h = 31*h + val[off++]; } hash = h; } return h; }
Take the string "123" as an example:
The ASCII code of '1' is 49.
Hashcode = (49*31 + 50) * 31 + 51
You can also see:
Hashcode = ('1' * 31 + '2') * 31 + '3'
It can be seen that the algorithm is actually a weight algorithm, and the weight of the previous character is large.
The obvious advantage is that the hash values of strings with the same prefix fall in the adjacent interval.
There are two advantages:
1. Memory saving, because the hash value is adjacent, so that the hash array can be relatively small. For example, when hashmap is used and string is the key.
2. the hash value is adjacent. If it is stored in a container, the actual memory location is also adjacent to the hashset and hashmap values, the access efficiency is also high. (Program Locality Principle)
Take 31 as a multiple, because the binary values of 31 are all 1, the data can be effectively discrete.
Finally, let's take a look at how the code generated by ECLIPSE calculates the hash value for two strings:
public class Name{String firstName;String lastName;@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result+ ((firstName == null) ? 0 : firstName.hashCode());result = prime * result+ ((lastName == null) ? 0 : lastName.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Name other = (Name) obj;if (firstName == null) {if (other.firstName != null)return false;} else if (!firstName.equals(other.firstName))return false;if (lastName == null) {if (other.lastName != null)return false;} else if (!lastName.equals(other.lastName))return false;return true;}}
It can be seen that it is still a multiple of 31, hashcode = firstname. hashcode () * 31 + lastname. hashcode ().
BTW: If the hash of the Java string is cached, it will be calculated for the first time. In the future, it will take the cached value.
The equals function generated by eclipse is of high quality and has been taken into account in various situations.
Conclusion: The string hash function should not only reduce conflicts, but also note that the hash values generated by strings with the same prefix must be adjacent.