Reputation: 115
Why in Java one null key is allowed in Hashmap, while in case of Hashtable it is not allowed ?
Upvotes: 1
Views: 304
Reputation: 4509
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..
Upvotes: 0
Reputation: 413
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
Upvotes: 0
Reputation: 121998
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
.
Upvotes: 1