HashMap与Hashtable的区别

两者的区别主要集中以下几个方面:

1.key是否允许为空

HashMap允许key为null,Hashtable不允许key为null。

2.value是否允许为空

HashMap允许value为空,Hashtbale不允许value为null。

3.线程是否安全

HashMap线程不安全,Hashtable线程安全。

4.Hashtable部分源码:

//使用了同步机制,线程安全
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {//value不允许为null
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry<?,?> tab[] = table;
        int hash = key.hashCode();//key不能为null
        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;
    }
原文地址:https://www.cnblogs.com/tonghun/p/7060834.html