Why in Java one null key is allowed in Hashmap, while in case of Hashtable it is not allowed ?
-
1The question is a duplicate of this– KurinchiMalarCommented Sep 23, 2015 at 11:06
-
1possible duplicate of Why does Hashtable not take null key?– AndiGeekyCommented Sep 23, 2015 at 11:10
-
Hashtable is older where as HashMap is newer as it was added in 1998. When they implemented HashMap they wanted to lift some of the limitations of Hashtable.– Peter LawreyCommented Sep 23, 2015 at 13:01
3 Answers
http://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
If you look at docs of HashMap
The
HashMap
class is roughly equivalent toHashTable
, except that it is unsynchronized and permitsnull
's.)
HashTable
is the older version of HashMap
which failed in that case of handling null
's. And HashMap
got that feature added into it to get more advanced than HashTable
.
HashMap allows the null key. If you try to insert the another value of same key, it will override it.
Incase of HashTable, put(K key, V value) throws the Null pointer Exception if the key or value is null.
Refer the source code. HashMap: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8-b132/java/util/HashMap.java#HashMap.put%28java.lang.Object%2Cjava.lang.Object%29
Hash table is very old class , from JDK 1.0
To understand this, first of all you need to understand comments written on this class by author.
This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.
HashTable
class is implemented on hashing mechanism, that’s mean to store any key-value pair, its required hash code of key object. If key would be null, it will not able to given hash ,it will through null pointer exception and similar case for value it is throwing null if the value is null.
But later on it was realized that null key and value has its own importance that is why one null key and multiple null values are allowed in later implemented classes like HashMap
class.
For hash map null keys will allow and there is a null check is there for keys if the key is null then that element will be stored in a zero location in Entry array. null key we can use for some default value..