• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

query regarding null key in hashmap

 
shreyans ricky
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am aware that we can have 1 null key in a hashmap.
If I try to put second null key in the hashmap, previous one is overridden.
Hashmap performs all the operation by evaluating the keys for methods hashcode and equals to check the existance of key.
My question here is: Is it possible to take hashcode of null value ?
If yes, how ?
If no, how does duplicate null key is avoided in the hashmap ??

Sample code :

Map<String, Integer> map = new HashMap<String, Integer>();

// put null key
map.put(null , 6);
// put duplicate key
map.put(null , 9);

Iterator<String> itr = map.keySet().iterator();
while (itr.hasNext()) {
String str = itr.next();
System.out.println(map.get(str));
}

The output will be 9




Regards,
Shreyans
 
William Brogden
Author and all-around good cowpoke
Rancher
Posts: 13074
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Browsing the source code for HashMap.java I find special handling of the null key - for example in the get method:



Bill

 
shreyans ricky
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bill !!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic