JAVA_HashMap的key允许空值而HashTable不允许

参考链接:

https://blog.csdn.net/codeHaoHao/article/details/85392932

为什么HashMap的key允许空值,而HashTable却不允许。。

 

 

 

HashMap 源码:

 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
 }

  */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

HashMap在put的时候会调用hash()方法来计算key的hashcode值,可以从hash算法中看出当key==null时返回的值为0。

因此key为null时,hash算法返回值为0,不会调用key的hashcode方法。

HashTable源码:

public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();
        int index = (hash & 0x7FFFFFFF) % tab.length;
        @SuppressWarnings("unchecked")
        Entry<K,V> entry = (Entry<K,V>)tab[index];
        for(; entry != null ; entry = entry.next) {
            if ((entry.hash == hash) && entry.key.equals(key)) {
                V old = entry.value;
                entry.value = value;
                return old;
            }
        }

        addEntry(hash, key, value, index);
        return null;
    }

上面可以看出当HashTable存入的value为null时,抛出NullPointerException异常。

如果value不为null,而key为空,在执行到int  hash = key.hashCode()时同样会抛出NullPointerException异常

2.从设计师角度分析
HashTable是Java中的遗留类,现在不怎么用了,这里HashMap vs HashTable有个解释。也许HashTable类的设计者当时认为null作为key 和value 是没有什么用的。

HashMap是之后的版本引进的类,它的接口Map表达的意义更为广泛,也许HashMap的设计者认为null作为key和value是有实际意义的,所以才允许为null.

当然实际项目中,真的是有value为null的情况的。key为null的情况比较少见,但不代表没有。HashMap允许null为key和value应当是类的设计者思考让这个类更有用的设计吧。

 

posted @ 2021-05-05 21:54  I_PENCIL  阅读(336)  评论(0编辑  收藏  举报