I made this function and it works the same as Original Java function when you input something short, but if i input something larger than 5-7 characters - then I get some realy big number. (And not the right hashcode)
Here is the formula of Java's hash function:
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
Simplier one (Only works for short strings):
s = "abc" //String
n = 3 //Lenght of the String
s[0] = 'a'. ASCII code of 'a' = 97.
97 * (31 ^ (n - 1))
97 * (31 ^ (2))
97 * 961 = 93217
s[1] = 'b'. ASCII code of 'b' = 98.
98 * (31 ^ (n - 2))
98 * (31 ^ 1)
98 * 31 = 3038
s[2] = 'c'. ASCII code of 'c' = 99.
99 * (31 ^ (n - 3))
99 * (31 ^ 0)
99 * 1 = 99
93217 + 3038 + 99 = 96354 //
I want to know how does Java makes hash small even when I enter a huge string.
Java's hashcode of "Hello" - 69609650
My hashcode of "Hello" - 69609650
Java's hashcode of "Welcome to Tutorialspoint.com" - 1186874997
My hashcode of "Welcome to Tutorialspoint.com" - 5.17809991536626e+43
Also how can hash be negative if we add up numbers ?