1

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

Daniel Rosano
  • 695
  • 5
  • 16
  • 1
    The question is a duplicate of [this](http://stackoverflow.com/questions/11981852/why-hashtable-does-not-allows-null-keys-or-values) – KurinchiMalar Sep 23 '15 at 11:06
  • 1
    possible duplicate of [Why does Hashtable not take null key?](http://stackoverflow.com/questions/7556357/why-does-hashtable-not-take-null-key) – AndiGeeky Sep 23 '15 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 Lawrey Sep 23 '15 at 13:01

3 Answers3

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.

Kruti Patel
  • 1,422
  • 2
  • 23
  • 36
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
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..

YoungHobbit
  • 13,254
  • 9
  • 50
  • 73
soorapadman
  • 4,451
  • 7
  • 35
  • 47
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

Thanigai Arasu
  • 413
  • 3
  • 14