I am curious how java generates hash values by using hashCode() method of the Object API ?
In HashMap, hashCode() is used to calculate the bucket and therefore calculate the index. equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation.
They use hashCode() method to check hash values. The default implementation of hashCode() in Object class returns distinct integers for different objects. Sometimes, we have to implement hashCode method in our program.
Java hashCode() Java Object hashCode() is a native method and returns the integer hash code value of the object. The general contract of hashCode() method is: Multiple invocations of hashCode() should return the same integer value, unless the object property is modified that is being used in the equals() method.
A hashcode is an integer value associated with every object in Java, facilitating the hashing in hash tables. To get this hashcode value for an object, we can use the hashcode() method in Java. It is the means hashcode() method that returns the integer hashcode value of the given object.
The hashCode()
of Object
is actually a native method and the implementation is actually not pure Java. Now, regarding the how it works, this answer from Tom Hawtin does a great job at explaining it:
Many people will claim that
Object.hashCode
will return the address of the object representation in memory. In modern implementations objects actually move within memory. Instead an area of the object header is used to store the value, which may be lazily derived from the memory address at the time that the value is first requested.
The whole answer is actually worth the read.
Java doesn't generate hashCode(), i.e. nothing automatic is happening here. However, Object
generates a HashCode based on the memory address of the instance of the object. Most classes (especially if you are going to use it in any of the Collection
API) should implement their own HashCode (and by contract their own equals method).
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