I want to get a unique hex per unique string. As of now I am using Message Digest class but there are possibilities (very less but still) that for two unique strings, computed hex can be same. So is there any other way to do such thing so that I have unique hex for unique strings.
Thanks in advance.
(Assuming that you meant
hash
, nothex
, since you mentioned MessageDigest).You can't have a unique hash code for each unique string. Think of it this way: A hash function maps a string (or any other object) to an integer number. Since each integer number can be represented as a string, e.g.
"123"
, there are at least as many strings as there are different integer numbers -- and then some more, like, everything that is not a number, e.g."Hello"
. Thus, as there are more strings than integer numbers, it is not possible to generate unique hash codes for unique strings in all cases.Having said that, for "everyday hashing" (for hash-tables etc.), the hash function provided by
String.hashCode
is about as good as it gets. For cryptographic hashing,MessageDigest
seems to be the way to go. Depending on what you currently use, you might be able to upgrade to a stronger algorithm, though, e.g.sha-512
instead ofsha-256
.