2.Map中hashMap和hashTable两个的对比

我们来对比一下hashMap和hashTable吧:

1.hashMap允许键值可以为空,hashTable键和值都不可以为空为什么这样呢,我们来看一下他们的put方法的源码。

先看hashMap的put方法:

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

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

在这里可以看出它对key=null的情况做了处理。再从putVal 方法中,没有对value直接引用,所以value为空也没影响。

再来看看hashTable的put方法:

 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;
}

put源码可以看出,当value为空时,会报NullPointerException异常,然后因为调用了key.hashCode(); 所以key为空的话,也会报空指针异常。

所以这就是为什么hashMap允许键、值可以为空,hashTable键和值都不可以为空的原因了。

2.hashTable 线程安全 :比如它的putget都使用了synchronized描述符。而遍历视图比如keySet都使用了Collections.synchronizedXXX进行了同步包装。

原文地址:https://www.cnblogs.com/WNof11020520/p/8757590.html