• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

HashMap question

 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have the following sections of code:






How is the hash code coming into play here? I have been used to a Map as simply a key/value pair type of table, but I am not sure how the hash code is being used.


 
Henry Wong
author
Marshal
Pie
Posts: 21489
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rachel Glenn wrote:I have the following sections of code:





How is the hash code coming into play here? I have been used to a Map as simply a key/value pair type of table, but I am not sure how the hash code is being used.


HashMaps only hash on the key, so in your example, the hashCode() method of the Dog class is not being used.

Henry
 
Rachel Glenn
Ranch Hand
Posts: 95
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. After doing some further reading I figured it out!!!
 
Prajwal Shetty
Ranch Hand
Posts: 35
Eclipse IDE Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We generally Override the hashCode() inorder to optimize the searching.
Consider the value returned by the hashCode() to be a bucket label.
So, In the example above you created only one Object of Dog "aiko" that was stored in bucket labelled '4'.

Please correct me Ranchers if I am wrong.
 
sakthi FrontTech
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
We generally Override the hashCode() inorder to optimize the searching.

If you see the HashMap implementation, hashCode of the object(say Dog Object in this case) will be manipulated again to avoid the weak hashCode implementation, so hashCode alone need not be the reason for optimize the searching, of Course its one of the reason. Refer below code




In the example above you created only one Object of Dog "aiko" that was stored in bucket labelled '4'.

In Java's HashMap implementation hashCode of the object doesn't specify the location or bucket the hash method pasted above will specify the location or bucket. The location or bucket will be changed when the threshHold percentage is reached.
If you want to know more about the HashMap please refer source of the HashMap.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic