Need help with this question What is the relationship betwe

Need help with this question :

What is the relationship between the hashCode () method defined for any Java object, and the hash function that is used to locate the object in a particular hashtable.

Solution

Here is example with explanation what hashcode and hash do:-

The default hashCode() of Object returns the memory address for the object.

So if you have the following class:

then create two objects:

car1.hashCode() will be different from car2.hashCode() because each object will have a different memory address.

What if you want both car1 and car2 to return the same hash code? In this case, you should override the default Object hashCode() method for the Car class as follows:

This will make car1.hashCode() equal to car2.hashCode() because the String.hashCode() calculates the hashCode based on the string contents, and the Integer.hashCode() will return the integer value itself.

In Java 7, you can just use Objects.hash(Object... values). So our new Car hashCode() will look as follows:

Objects.hash(Object... values) will call Arrays.hashCode for you.

Finally, Objects.hashCode(Object o) will do a null check. It will return 0 if the object is null. Else, it will call the objects hashCode() method.

Note that hash(o) and hashCode(o) won\'t necessarily return the same thing! If you\'re doing it for a single object, you should probably use hashCode.

Hope your query is cleared after reading this explanation.

Need help with this question : What is the relationship between the hashCode () method defined for any Java object, and the hash function that is used to locate

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site