Possible Duplicate:
How is hashCode() calculated in Java
I found there's no implementation in hashCode()
method of root class Object
in Java:
public native int hashCode();
If I have an Object a
and an Object b
, how can I know the a.hashCode()
and b.hashCode()
value without using System.out.println()
? Just by the hashCode
implementation.
I have try to new
two ArrayList
objects and to my big surprise the hashCode()
values are the same: both of them are 1.
Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode. public native int hashCode();
In Java, hashCode() by default is a native method, which means that the method has a modifier 'native', when it is implemented directly in the native code in the JVM. Used to digest all the data stored in an instance of the class into a single hash value i.e., a 32-bit signed integer.
1) If two objects are equal (i.e. the equals() method returns true), they must have the same hashcode. 2) If the hashCode() method is called multiple times on the same object, it must return the same result every time. 3) Two different objects can have the same hash code.
No, it will not allow duplicates. hashTable. put(key, value); If key is already present, existing value will be overridden by the new value for a given key and returns the old value.
hashCode
is a native
method which means that a system library is called internally. See Java Native Interface for more details.
There is a question on SO Why hashCode() and getClass() are native methods? Might be interesting for you.
The default hashCode is going to be implementation-specific. I suspect it's related to the memory address, but note that the VM moves objects around in memory (and, of course, the hashCode has to remain the same). So it won't be the actual memory address.
The default hashcode()
implementation frequently but not always provides an integer based loosely on the memory address of the object, however the memory address can change. This may vary based loosely upon the JVM implementation.
hashCode()
As you know this method provides the has code of an object. Basically the default implementation of hashCode() provided by Object is derived by mapping the memory address to an integer value. If look into the source of Object class , you will find the following code for the hashCode.
public native int hashCode();
It indicates that hashCode is the native implementation which provides the memory address to a certain extent. However it is possible to override the hashCode method in your implementation class.
http://www.javaworld.com/community/node/1006
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