• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

is it neccessary to overide the equals and hashcode method of value objects for doing get operation?

 
utsav gupta
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

On doing a get operation on a hashmap the key objects is taken, its hashcode function is called it's hashcode is compared to the hashcodes of the enetered keys by again calling the hascode function. On a match the key objects equals() function is called and then it is compared to the equals function of the stored key objects on a match again the value object is retrieved. In such a scenario why is it necessary to overide the equals and hashcode methods of the value objects? As the hashcode and equals methods of value object is never called?
please tell me if I am missing something.
Thanks
Utsav.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34669
367
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's not. Where did you read that you have to override equals/hashcode on the value? On the key it is a must - as you noted. But not on the value.

You may need to implement equals/hashcode based on what you later do with the value, but not for the purposes of the map.
 
utsav gupta
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Jeanne

Thanks for clarifying that out. I just saw a code snippet on the net which had it like that.
 
Saifuddin Merchant
Ranch Hand
Posts: 607
Firefox Browser Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nonetheless over-ridding the equals method is a very normal requirement for most classes even if the class just participates as a 'value' in the hashmap. Of course if you override equals you **must** override hash code!!

 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also, the term "value object" should probably be avoided here, as it has two other meanings which have nothing to do with HashMaps. The correct meaning is this one, while the sadly better-known meaning is this one. Note that the second meaning has now been renamed Data Transfer Object, but people still erroneously use the term Value Object here. Anyway, best to avoid the term here as neither meaning seems to be what you mean here.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic