Formula
This method computes the hash code for a String. The hash code for a String object is calculated as:
| |
In this formula:
s[i]denotes the ith character of theString(using zero-based indexing).nis the length of theString.^denotes exponentiation.
Using integer arithmetic, the Java hashCode() method iterates over each character of the String and calculates the hash value. For an empty string, the hash code is defined to be 0.
Formula in integer arithmetic
The implementation uses integer arithmetic to avoid potential overflow issues by utilizing a prime number 31 in the calculation, which tends to provide a better distribution of hash values. The final formula looks like this using integer arithmetic:
| |
Breakdown of the Formula
Here’s a step-by-step explanation of how the hash code is computed for the string “hello”:
- Characters:
h = 104,e = 101,l = 108,l = 108,o = 111 - Length (
n): 5
Using the formula:
| |
The hash code for the string “hello” is computed as hash = 99253161.
Implementation of hashCode() in Java String class
| |
hstarts at0.- It iterates through each character of the string, multiplying the current hash by
31and adding the ASCII value of the character.
Example Usage
| |
Explanation:
- A string
"Welcome to k5kc.com"is created. - The
hashCode()method is called on this string. - The hash code is printed.
Summary
The hashCode() method in Java’s String class uses a precise and efficient algorithm to compute a hash value based on the prime number 31. This helps in achieving a good distribution of hash values, thereby minimizing collisions in hash-based collections like HashMap and HashSet.
This method is both efficient and effective, ensuring that Java developers can trust the hashCode() method to provide consistent and well-distributed hash values for strings.