Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the time complexity of Java hashCode method for the String class?

Tags:

java

Is Java's hashCode method for String class computed in constant time or linear time? What is the algorithm used?

like image 833
Ramesh Singh Avatar asked Jan 21 '16 05:01

Ramesh Singh


People also ask

What is the time complexity of hashing a string?

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.

What is hashCode of string in Java?

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.

Why does Java use 31 in the hashCode () for string?

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.

What is the return time of the hashCode method in the object class?

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.


2 Answers

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.

like image 126
Louis Wasserman Avatar answered Oct 20 '22 10:10

Louis Wasserman


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).

like image 3
Atri Avatar answered Oct 20 '22 10:10

Atri