Is Java's hashCode method for String class computed in constant time or linear time? What is the algorithm used?
The complexity of a hashing function is never O(1). If the length of the string is n then the complexity is surely O(n). However, if you compute all hashes in a given array, you won't have to calculate for the second time and you can always compare two strings in O(1) time by comparing the precalculated hashes.
Java String hashCode() Method The hashCode() method returns the hash code of a string. The hash code for a String object is computed like this: s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation.
The value 31 was chosen because it is an odd prime. If it were even and the multiplication overflowed, information would be lost, as multiplication by 2 is equivalent to shifting. The advantage of using a prime is less clear, but it is traditional.
The Java hashCode() Method hashCode in Java is a function that returns the hashcode value of an object on calling. It returns an integer or a 4 bytes value which is generated by the hashing algorithm.
The documentation tells you the function:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
It's computed once using a linear-time pass, and then cached so it's only O(1) to retrieve it in the future.
According to the docs
public int hashCode()
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
As you can see, the time complexity is the O(n) where n is the number of characters in the string. After one pass, it is cached so the time complexity is effectively O(1).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With