1

Why in Java one null key is allowed in Hashmap, while in case of Hashtable it is not allowed ?

3
  • 1
    The question is a duplicate of this Commented Sep 23, 2015 at 11:06
  • 1
    possible duplicate of Why does Hashtable not take null key?
    – AndiGeeky
    Commented 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. Commented Sep 23, 2015 at 13:01

3 Answers 3

1

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 to HashTable, except that it is unsynchronized and permits null'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.

0

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

HashTable: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Hashtable.java#Hashtable.put%28java.lang.Object%2Cjava.lang.Object%29

0

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..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.