5

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?

Raj
  • 672
  • 2
  • 8
  • 22
  • You don't have to override these, but the class you use e.g. `String` has to override these and it does so already. You only needed to do it if you create your own key class. BTW Most IDEs can generate these for you (so you don't need to write them yourself) – Peter Lawrey Sep 04 '13 at 06:09
  • 1
    None of the answers to that other question specifically address this one; because its NOT a duplicate. Please join me in voting to reopen this, to undo the erroneous closure. – Dawood ibn Kareem Sep 04 '13 at 06:22
  • @tDavid I raised this question after reading all answers only. I could not find answer of my question. – Raj Sep 04 '13 at 07:12

1 Answers1

3

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

Prasad Kharkar
  • 12,721
  • 3
  • 35
  • 55