There seems to be an ongoing debate about whether it is safe to rely on the current implementation of String.hashCode()
because, technically speaking, it is guaranteed by the specification (Javadoc).
String.hashCode()
's implementation in the specification?String.hashCode()
is changed in the future? (This is probably be explained by #2)The purpose of the hashCode() method is to provide a numeric representation of an object's contents so as to provide an alternate mechanism to loosely identify it. By default the hashCode() returns an integer that represents the internal memory address of the object.
The general contract of hashCode is: During the execution of the application, if hashCode() is invoked more than once on the same Object then it must consistently return the same Integer value, provided no information used in equals(Object) comparison on the Object is modified.
Uses of hashCode() and equals() Methods Its default implementation simply checks the object references of two objects to verify their equality. By default, two objects are equal if and only if they are refer to the same memory location. Most Java classes override this method to provide their own comparison logic.
The Java String hashCode() method returns a hash code for the string. A hashcode is a number (object's memory address) generated from any object, not just strings. This number is used to store/retrieve objects quickly in a hashtable. The syntax of the string hashCode() method is: string.hashCode()
A reason for relying on the specific implementation of hashCode() would be if it is ever persisted out into a database, file or any other storage medium. Bad Things(tm) would happen if the data was read back in when the hashing algorithm had changed. You could encounter unexpected hash collisions, and more worryingly, the inability to find something by its hash because the hash had changed between the data being persisted and "now".
In fact, that pretty much explains point #3 too =)
The reason for point #1 could be "to allow interoperability". If the hashCode implementation is locked down then data can be shared between different implementations of Java quite safely. i.e, the hash of a given object will always be the same irrespective of implementation.
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