Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is necessary to override hashcode and equals method of key for Hashmap? [duplicate]

I created a HashMap having Student as key and String as value.

Now everywhere i have read It is necessary to override equals and hashcode method if using as a key for hashmap.

But I did not override it. And insert multiple key value pairs in hashmap. I am also able to fetch it back.

So why it is necessary?

like image 523
Raj Avatar asked Oct 21 '22 01:10

Raj


1 Answers

They are required when you want to use your objects as useful hashing keys into collections that use hashing.

Have your tried to add the Student objects which are meaningfully equal? First understand the significance of equals method in java

Read the significance of equals and hashcode

like image 136
Prasad Kharkar Avatar answered Oct 27 '22 11:10

Prasad Kharkar