Is the output of Object.hashCode()
required to be the same on all JVM implementations for the same Object?
For example if "test".hashCode()
returns 1
on 1.4, could it potentially return 2
running on 1.6. Or what if the operating systems were different, or there was a different processor architecture between instances?
Whenever it is invoked on the same object more than once during an execution of a Java application, hashCode() must consistently return the same value, provided no information used in equals comparisons on the object is modified.
If multiple objects return the same value from hashCode(), it means that they would be stored in the same bucket. If many objects are stored in the same bucket it means that on average it requires more comparison operations to look up a given object.
Unequal objects must have different hash codes – WRONG! Objects with the same hash code must be equal – WRONG!
General contract associated with hashCode() methodIf two objects are equal(according to equals() method) then the hashCode() method should return the same integer value for both the objects.
No. The output of hashCode
is liable to change between JVM implementations and even between different executions of a program on the same JVM.
However, in the specific example you gave, the value of "test".hashCode()
will actually be consistent because the implementation of hashCode
for String
objects is part of the API of String
(see the Javadocs for java.lang.String and this other SO post).
From the API
The general contract of hashCode is:
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
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