What value does the hashCode()
method return in java?
I read that it is a memory reference of an object… The hash value for new Integer(1)
is 1; the hash value for String("a")
is 97.
I am confused: is it ASCII or what type of value is?
hashcodejava
What value does the hashCode()
method return in java?
I read that it is a memory reference of an object… The hash value for new Integer(1)
is 1; the hash value for String("a")
is 97.
I am confused: is it ASCII or what type of value is?
Best Answer
The value returned by
hashCode()
is by no means guaranteed to be the memory address of the object. I'm not sure of the implementation in theObject
class, but keep in mind most classes will overridehashCode()
such that two instances that are semantically equivalent (but are not the same instance) will hash to the same value. This is especially important if the classes may be used within another data structure, such as Set, that relies onhashCode
being consistent withequals
.There is no
hashCode()
that uniquely identifies an instance of an object no matter what. If you want a hashcode based on the underlying pointer (e.g. in Sun's implementation), useSystem.identityHashCode()
- this will delegate to the defaulthashCode
method regardless of whether it has been overridden.Nevertheless, even
System.identityHashCode()
can return the same hash for multiple objects. See the comments for an explanation, but here is an example program that continuously generates objects until it finds two with the sameSystem.identityHashCode()
. When I run it, it quickly finds twoSystem.identityHashCode()
s that match, on average after adding about 86,000 Long wrapper objects (and Integer wrappers for the key) to a map.Example output: