Why does Hashtable not take null key?

后端 未结 6 1018
傲寒
傲寒 2020-12-08 05:35

Why does Hashtable not take a null key?

Also why does HashMap allow null keys?

What is the purpose of making these two classes Key

6条回答
  •  悲&欢浪女
    2020-12-08 06:21

    From the Hashtable JavaDoc:

    To successfully store and retrieve objects from a hashtable, the objects used 
    as keys must implement the hashCode method and the equals method.
    

    In a nutshell, since null isn't an object, you can't call .equals() or .hashCode() on it, so the Hashtable can't compute a hash to use it as a key.

    HashMap is newer, and has more advanced capabilities, which are basically just an improvement on the Hashtable functionality. As such, when HashMap was created, it was specifically designed to handle null values as keys and handles them as a special case.

    Specifically, the use of null as a key is handled like this when issuing a .get(key):

    (key==null ? k==null : key.equals(k))
    

提交回复
热议问题