| Author |
Hashtable doesn't allow null value and HashMap allows only one null as key
|
Harikrishna Gorrepati
Ranch Hand
Joined: Sep 23, 2010
Posts: 422
|
|
|
Hi, Could you please advice the reason behind why Hashtable doesn't allow null value and HashMap allows only one null as key
|
OCPJP 6.0-81% | Preparing for OCWCD
http://www.certpal.com/blogs/cert-articles | http://sites.google.com/site/mostlyjava/scwcd |
|
 |
Tom Reilly
Rancher
Joined: Jun 01, 2010
Posts: 618
|
|
|
Because the keys must be unique. Therefore, you can only have one key that is null.
|
 |
Harikrishna Gorrepati
Ranch Hand
Joined: Sep 23, 2010
Posts: 422
|
|
Tom Reilly wrote:Because the keys must be unique. Therefore, you can only have one key that is null.
So, why Hashtable doesn't allow null value at all
|
 |
Tom Reilly
Rancher
Joined: Jun 01, 2010
Posts: 618
|
|
So, why Hashtable doesn't allow null value at all
I'll turn it back on you. Why would HashMap allow a null key?
|
 |
Harikrishna Gorrepati
Ranch Hand
Joined: Sep 23, 2010
Posts: 422
|
|
Because Keys must be unique in Map. HashMap can have maximum one null value
Tom Reilly wrote:
So, why Hashtable doesn't allow null value at all
I'll turn it back on you. Why would HashMap allow a null key?
|
 |
Abimaran Kugathasan
Ranch Hand
Joined: Nov 04, 2009
Posts: 2066
|
|
From the APIs, we can see, the objects which stored in the Hashtable should implement hashCode() and equals() methods.
To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.
But, However the HashMap implementation does allow null keys. In the java.util.HashMap implementation, in case the key is null, it uses a surrogate object to act as the key. The surrogate key is a dummy non-null java object. However using a null key in HashMap overwrites the previous null-key : value mapping.
I think, it should be the reason.
|
|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
|
 |
Jaikiran Pai
Marshal
Joined: Jul 20, 2005
Posts: 8142
|
|
There are many previous discussions about this in the "Beginning Java" and "Java In General" forums, including this one http://www.coderanch.com/t/409245/java/java/Why-does-HashMap-allow-null
|
[My Blog] [JavaRanch Journal]
|
 |
 |
|
|
subject: Hashtable doesn't allow null value and HashMap allows only one null as key
|
|
|