This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Distributed Java and the fly likes query regarding null key in hashmap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Distributed Java
Bookmark "query regarding null key in hashmap" Watch "query regarding null key in hashmap" New topic
Author

query regarding null key in hashmap

shreyans ricky
Greenhorn

Joined: May 29, 2009
Posts: 8
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

Joined: Mar 22, 2000
Posts: 12761
    
    5
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

Joined: May 29, 2009
Posts: 8
Thanks Bill !!
 
 
subject: query regarding null key in hashmap
 
Similar Threads
Code to store null keys and null values in hashmap
Working with HashMap
Working with HashMap
HashMap and hashCode method
HashMap remove multiple elements