Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does the hashCode() method of java works?

I am curious how java generates hash values by using hashCode() method of the Object API ?

like image 969
Hellnar Avatar asked Dec 24 '09 22:12

Hellnar


People also ask

How hashCode () and equals () methods are used in HashMap?

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.

Why hashCode method is used?

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.

What is the hashCode () and equals () used for?

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.

Where do we use hashCode in Java?

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.


2 Answers

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.

like image 117
Pascal Thivent Avatar answered Oct 10 '22 16:10

Pascal Thivent


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).

like image 24
MarkPowell Avatar answered Oct 10 '22 15:10

MarkPowell