## HashTable和HashMap的区别

HashTable和HashMap的区别

说明:本文源码及源码注释基于jdk1.8.0_151

1.继承类不同

HashTable继承自Dictionary,而HashMap继承自AbstractMap。Dictionary已经被废弃。

/**
 * Hash table based implementation of the <tt>Map</tt> interface.  This
 * implementation provides all of the optional map operations, and permits
 * <tt>null</tt> values and the <tt>null</tt> key.  (The <tt>HashMap</tt>
 * class is roughly equivalent to <tt>Hashtable</tt>, except that it is
 * unsynchronized and permits nulls.)  This class makes no guarantees as to
 * the order of the map; in particular, it does not guarantee that the order
 * will remain constant over time.
 **/
 //HashMap大致相等于HashTable,除了不同步(不线程安全)和允许为null。
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
...
}
public class Hashtable<K, V> extends Dictionary<K, V> implements Map<K, V>, Cloneable, Serializable {
...
}

继续看Dictionary和AbstractMap的源码,Dictionary就是一个抽象类,废弃,而AbstractMap是实现接口Map的抽象类。

/** <strong>NOTE: This class is obsolete.  New implementations should
 * implement the Map interface, rather than extending this class.</strong>
 */
 //这个类已经过时了。新的实现应该实现MAP接口,而不是扩展这个类。
public abstract class Dictionary<K,V> {
...
}
public abstract class AbstractMap<K,V> implements Map<K,V> {
...
}

下面是他们的继承关系:
hashtable的继承图:

hashMap的继承图:

2.HashMap支持键值对为空,HashTable是同步的

从代码中看, Hashtable的put方法如果put一个null则抛出NullPointerException异常,而HashMap则是不会判断是否为null,可以插入null值。第二对于HashTable,方法前加入synchronized,是同步的。

public class Hashtable<K, V> extends Dictionary<K, V> implements Map<K, V>, Cloneable, Serializable {
 ...
   public synchronized V put(K var1, V var2) {
        if (var2 == null) {
            throw new NullPointerException();
        } else {
            ...
        }
    }
}
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
  public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
  /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //判断tab是否为空,是否还有剩余空间
        if ((tab = table) == null || (n = tab.length) == 0)
            //扩容
            n = (tab = resize()).length;
        //判断tab是否为空
        if ((p = tab[i = (n - 1) & hash]) == null)
            //创建一个Node,可以传null值进去
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            //比较哈希值是否相同,比较key实例是否相同,比较key值是否相同
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //如果p是TreeNode(LinkedHashMap)
            else if (p instanceof TreeNode)
                //在红黑树中插入键值对
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            ////如果链表的长度大于TREEIFY_THRESHOLD,转成红黑树
                            treeifyBin(tab, hash);
                        break;
                    }
                    //找到key,跳出循环
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            //为key赋值
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    //可以替换成null值
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }
}

总结:

1.HashMap是支持null键和null值的,而HashTable在遇到null时,会抛出NullPointerException异常。
2.HashTable是同步的,HashMap不同步,即HashMap不是线程安全的。
3.HashTable已经被废弃
该文为www.dengyouquan.cn原创
原文地址:https://www.cnblogs.com/sufferingStriver/p/9041166.html