Net-informations.com
SiteMap  | About    

Java hashCode()

Java.lang.Object has methods called hasCode() and this methods play a significant role in the real time application. The hashCode() of Object is actually a native method and the implementation is actually not in pure Java. If look into the source of Object Class , you can see the following code for the hashCode.

This 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. Native methods are either Intrinsic or written outside Java in "native" code, that is, specific to the given machine.

Java does not generate meaningful hashCode for you, it is your job as a developer to generate a useful hashCode. However, Object generates a HashCode based on the memory address of the instance of the object. Most classes (especially Collection API) should implement their own HashCode (and by contract their own equals method). The value returned by hashCode() is by no means guaranteed to be the memory address of the object. According to Java API, the calculation of hashcode is based on 32-bit internal JVM (Java Virtual Machine) address of the Object. It is true that the object moves during execution. But hashcode does not change.

Example

In the above case, student1.hashCode will not be equal to student2.hashCode because the memory addresses of these two objects are not the same. But student2.hashCode will be equal to student3 because they are pointing to the same object . So if you need to use hashCode method for your objects you must implement it yourself.

HashCode and Equals method in Java

In Java, every object has access to the equals() method because it is inherited from the Object class. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. You must override hashCode() in every class that overrides equals(). More about.... HashCode and Equals method







net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.