• Post Reply Bookmark Topic Watch Topic
  • New Topic

How HaspMap use null key , to calculate it's hashcode for storing in particular location?  RSS feed

 
Karn Kumar
Ranch Hand
Posts: 153
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

It is said that HashMap uses the hashcode() method of the key for determining the memory location where he can store the Object against that key.

For the non null keys object class hashcode() method will return some value which can be used to in storing the object in HashMap but in case of null key can anybody suggest that

how the memory location is detected ?


Thanks and Regards,
Chetan
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually, HashMap uses the hash code to determine where in memory the key itself is stored, not the value. So the HashMap can simply reserve a fixed slot for the null key.
 
Mike Simmons
Ranch Hand
Posts: 3090
14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually HashMap uses the hash code to determine the location in memory of a chain of HashMap.Entry objects, which contain one key and one value per Entry. There's no point in being able to find the key if you can't also find the value; that's why they store them both together.
 
Stephan van Hulst
Saloon Keeper
Posts: 7993
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Um, yes of course ^^;
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Whenever you have questions like these, you can go to your JDK folder, unpack the src.zip file located inside it, and check out the source code of the class.
 
Karn Kumar
Ranch Hand
Posts: 153
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All ,

The HashMap put() method has very first condition as



and in the putForNullKey() method the logic is implemented.

Regards,
Chetan
 
Seetharaman Venkatasamy
Ranch Hand
Posts: 5575
Eclipse IDE Java Windows XP
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
notable point is that first cell is always allocated to null key, hence null key object comes first in iteration!
 
Rob Spoor
Sheriff
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That's not guaranteed. Perhaps that's the case in the current implementation, but until it's mentioned in the Javadoc pages Oracle can change that whenever they see fit. After all, currently the Javadoc only says that the order is not guaranteed at all.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!