Win a copy of Svelte and Sapper in Action this week in the JavaScript forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Bear Bibeault
  • Junilu Lacar
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Tim Holloway
  • salvin francis
  • Frits Walraven
Bartenders:
  • Scott Selikoff
  • Piet Souris
  • Carey Brown

query regarding null key in hashmap

 
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
 
Author and all-around good cowpoke
Posts: 13078
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 !!
 
See ya later boys, I think I'm in love. Oh wait, she's just a tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
    Bookmark Topic Watch Topic
  • New Topic