Java doc for method String#hashCode() says:
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 ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
Questions:
I am not using it any where in code. I have just asked this question to know more about Java String class.
Is it possible to have same hash code for two string objects having different values? If yes then please share some examples.
Here is a small sample of randomly generated examples of short strings with identical hash codes:
String 1 String 2 Common hash code
-------- -------- ----------------
VTBHKIGV - FLXCLLII -1242944431
FPESRBAH - GNFWMYVA 1778061647
UYDHRTXL - HGCNRCBE 1509241566
VXQMFMDE - YMYXDWKK -1553987354
VGWBSYRX - JZNQSUXK 700334696
Since multiple strings can share the same hash code, restoring the original from the hash is not possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With