Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to get String value back from its hash code?

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:

  • Is it possible to have same hash code for two string objects having different values? If yes then please share some examples.
  • Is it possible to get String value back from its hash code?

I am not using it any where in code. I have just asked this question to know more about Java String class.

like image 702
Braj Avatar asked Dec 06 '25 05:12

Braj


1 Answers

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.

like image 166
Sergey Kalinichenko Avatar answered Dec 07 '25 18:12

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!