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 ?
I suspect your implementation (which you haven't shown) uses BigInteger
or something similar. Java just uses int
- so when it overflows the range of positive 31-bit integers, it goes into large negative integers, and then as you add more (positive) values, you'll end up with small negative integers, then small positive integers, then large positive integers - and back to large negative integers.
See more on this question at Stackoverflow