An interesting issue came up recently. We came across some code that is using hashCode()
as a salt source for MD5 encryption but this raises the question: will hashCode()
return the same value for the same object on different VMs, different JDK versions and operating systems? Even if its not guaranteed, has it changed at any point up til now?
EDIT: I really mean String.hashCode()
rather than the more general Object.hashCode()
, which of course can be overridden.
A code hash function always returns the unique hash value for every String value. The hashCode() method is the inherited method from the Object class in the String class that is used for returning the hash value of a particular value of the String type.
On strings, numbers and collection classes, hashCode() always returns a consistent value, apparently even across different JVM vendors.
The hashCode() method returns the hash code of a string. where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation.
No. From http://tecfa.unige.ch/guides/java/langspec-1.0/javalang.doc1.html:
The general contract of hashCode is as follows:
- Whenever it is invoked on the same object more than once during an execution of a Java application, hashCode must consistently return the same integer. The integer may be positive, negative, or zero. This integer does not, however, have to remain consistent from one Java application to another, or from one execution of an application to another execution of the same application. [...]
It depends on the type:
Just a cautionary tale from the .NET world: I've seen at least a few people in a world of pain through using the result of string.GetHashCode() as their password hash in a database. The algorithm changed between .NET 1.1 and 2.0, and suddenly all the hashes are "wrong". (Jeffrey Richter documents an almost identical case in CLR via C#.) When a hash does need to be stored, I'd prefer it to be calculated in a way which is always guaranteed to be stable - e.g. MD5 or a custom interface implemented by your types with a guarantee of stability.
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