Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java hashCode method maximum return value

Tags:

java

hash

Can someone tell me what are the maximum and minimum int values that the Java String.hashCode() method can return?

like image 583
William Seemann Avatar asked Jul 14 '12 00:07

William Seemann


3 Answers

String.hashCode () return an int calculated by using the below formula:

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]

using int arithmetic, where s[i] is the i-th character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)


The minimum and max value can be found with the below constants.

 System.out.println (java.lang.Integer.MAX_VALUE); //  2147483647
 System.out.println (java.lang.Integer.MIN_VALUE); // -2147483648
like image 50
Filip Roséen - refp Avatar answered Oct 20 '22 21:10

Filip Roséen - refp


Java int is 4 bytes, signed (two's complement). -2,147,483,648 to 2,147,483,647. Like all numeric types ints may be cast into other numeric types (byte, short, long, float, double). When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of the smaller type.

like image 3
Chimera Avatar answered Oct 20 '22 21:10

Chimera


From the documentation, given that the power to which something is raised depends on the length of the String (which is practically unlimited, as far as I know), I would say that the maximum and minimum must be Integer.MAX_VALUE (2^31 - 1) and Integer.MIN_VALUE (-2^31), respectively.

like image 2
CosmicComputer Avatar answered Oct 20 '22 20:10

CosmicComputer