Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hashtable and Hashmap Doubt

 
Abhi vijay
Ranch Hand
Posts: 509
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read in K&B Book that,

Hashmap allows one null key and multiple null values in a collection. wheras Hashtable dosent let you add anything that's null.


Why is this distinction as both are unsorted, unordered?
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hashtable is thread-safe Abhi, and it was there in java since 1.0, you can see its naming convention "t" in Hashtable is written in small. It was designed such that it will not allow any null key or null value.


But HashMap is added in java 1.2 version, so designer thought null should be allowed. Reason I do not know, any sheriff or knowledgeable guy could say the reason.


 
Duran Harris
Ranch Hand
Posts: 608
Eclipse IDE Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Punit,

You just inserted MULTIPLE null keys into the hashMap...
why was there no exception?
 
Punit Singh
Ranch Hand
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HashMap does not store duplicate values. So although I have inserted multiple key, it will store only one null key and set the latest value to it.

Run this code, and tell me what you learned ?
 
Vijitha Kumara
Bartender
Posts: 3914
9
Chrome Fedora Hibernate
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Duran Harris wrote:

You just inserted MULTIPLE null keys into the hashMap...
why was there no exception?


If the map previously contained the same key the old value is replaced.
 
Duran Harris
Ranch Hand
Posts: 608
Eclipse IDE Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh ok...Got it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic