• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Tim Cooke
  • Devaka Cooray
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • Piet Souris
  • Mikalai Zaikin
Bartenders:
  • Carey Brown
  • Roland Mueller

query regarding null key in hashmap

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Author and all-around good cowpoke
Posts: 13078
6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Bill !!
 
Do Re Mi Fa So La Tiny Ad
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic