+ 1

hashCode() method in Java (overriding)

While we need to override the equals() method, we also have to override hashCode() method... But why?? What is hashCode() method and why to override it while overriding the equals method? and if possible.. also explain how to override it...

8th Jul 2018, 6:50 AM
Jain Rishav Amit
Jain Rishav Amit - avatar
3 Antworten
+ 1
you need to override both if you are using a map and along with manual object, say user class, and you are using user object as a key in map, then while adding to map, java will use the hascode method to create a bucket and it will store your object in that, that hascode method will give unique code as it depends on us how to implement it, and if the bucket is created then equals is called to check whether the already existing object is equal to the new which ur adding, if it is same then it will replace the old with this new one, if it is not then it will add that object. now the next step is while you fetch the object, you will fetch by using user object which you are using as a key, again java will call hashcode method to found the bucket then use the equals method to check whether the key matches, and if that matches then you will get the object which u have added as a value. note: if 2 objects are equal then their hashcode will be equal, vice versa is not true
8th Jul 2018, 3:15 PM
Atishay Jain
Atishay Jain - avatar
+ 1
thanks Atishay Jain for the detailed explanation but i am not yet clear with the concept
10th Jul 2018, 4:47 AM
Jain Rishav Amit
Jain Rishav Amit - avatar
0
if you override the hashcode but didn't override equals in above case then in some scenario, you will not be able to get your object which u added as a value in your map. try this scenario.
8th Jul 2018, 3:17 PM
Atishay Jain
Atishay Jain - avatar