0

Can anyone please tell me what does the hashCode() method of String class contain?

and what kind of value it returns. in a normal class, if I call hashCode() method it returns the address of the object in decimal format. But for string class it is different. can anyone please explain it to me.

30th Jul 2017, 4:24 PM
Devbrath
Devbrath - avatar
4 ответов
+ 2
"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. A nice property of 31 is that the multiplication can be replaced by a shift and a subtraction for better performance: 31 * i == (i << 5) - i. Modern VMs do this sort of optimization automatically." From: https://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier From From: A book 😜
30th Jul 2017, 6:16 PM
Rrestoring faith
Rrestoring faith - avatar
+ 2
It returns the hashcode. Hashcode is calculated by: Quoted from Oracle: " s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)"
30th Jul 2017, 5:59 PM
Rrestoring faith
Rrestoring faith - avatar
0
and why 31? why not other number?
30th Jul 2017, 6:01 PM
Devbrath
Devbrath - avatar
0
thnx
30th Jul 2017, 6:21 PM
Devbrath
Devbrath - avatar