Hashtable 源码解析

260 阅读3分钟
知乎:zhuanlan.zhihu.com/p/77706764

前言

注意是 `Hashtable` 不是 `HashTable` (t为小写),这不是违背了驼峰定理了嘛?这还得从 `Hashtable` 的出生说起,
`Hashtable` 是在Java1.0的时候创建的,而集合的统一规范命名是在后来的Java2开始约定的,而当时又发布了新的集合代替它,所以这个命名也一直使用到现在,
所以 `Hashtable` 是一个过时的集合了,不推崇大家使用这个类,虽说 `Hashtable` 是过时的了,我们还是有必要分析一下它,以便对Java集合框架有一个整体的认知。
  • `HashTable` 比较古老, 是JDK1.0就引入的类,而` HashMap` 是 1.2 引进的 Map 的一个实现。
  • `HashTable` 是线程安全的,能用于多线程环境中。
  • `Hashtable` 同样也实现了 `Serializable` 接口,支持序列化,也实现了 `Cloneable` 接口,能被克隆。

成员变量

//为什么要用int最大值-8,官方解释:有些虚拟机在数组中保留了一些头信息。避免内存溢出!
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//table是一个Entry[]数组类型,而Entry实际上就是一个单向链表。哈希表的"key-value键值对"都是存储在Entry数组中的。
private transient Entry[] table; 
// Hashtable中元素的实际数量 
private transient int count; 
// 阈值,用于判断是否需要调整Hashtable的容量(容量*加载因子 >= threshold 是需要调整容量) 
private int threshold; 
// 加载因子 默认0.75f
private float loadFactor; 
// Hashtable被改变的次数 是Hashtable被修改或者删除的次数总数。用来实现“fail-fast”机制的
private transient int modCount = 0;

public Hashtable(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                                           initialCapacity);
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal Load: "+loadFactor);
    //初始容量最小为1
    if (initialCapacity==0)
        initialCapacity = 1;
    this.loadFactor = loadFactor;
    table = new Entry<?,?>[initialCapacity];
    threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
}

PUT方法

  • 线程安全
  • key value 都不能为null
  • hash & 0x7FFFFFFF 是为了避免负数,为什么不用abs(绝对值)?涉及一个int负数最大值问题
  • 如果key已存在会返回老的value
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;
}

addEntry方法

  • 如果hashtable 当前数量>=阈(愈)值,需要扩容
  • 链表叠加
private void addEntry(int hash, K key, V value, int index) {
    modCount++;

    Entry<?,?> tab[] = table;
    if (count >= threshold) {
        // Rehash the table if the threshold is exceeded
        rehash();

        tab = table;
        hash = key.hashCode();
        index = (hash & 0x7FFFFFFF) % tab.length;
    }

    // Creates the new entry.
    @SuppressWarnings("unchecked")
    Entry<K,V> e = (Entry<K,V>) tab[index];
    tab[index] = new Entry<>(hash, key, value, e);
    count++;
}

rehash方法

  • 容量扩大两倍+1
  • 需要将原来HashTable中的元素一一复制到新的HashTable中,这个过程是比较消耗时间的
  • 链表顺序变了
@SuppressWarnings("unchecked")
protected void rehash() {
    int oldCapacity = table.length;
    Entry<?,?>[] oldMap = table;

    // overflow-conscious code
    int newCapacity = (oldCapacity << 1) + 1;
    if (newCapacity - MAX_ARRAY_SIZE > 0) {
        if (oldCapacity == MAX_ARRAY_SIZE)
            // Keep running with MAX_ARRAY_SIZE buckets
            return;
        newCapacity = MAX_ARRAY_SIZE;
    }
    Entry<?,?>[] newMap = new Entry<?,?>[newCapacity];

    modCount++;
    threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
    table = newMap;

    for (int i = oldCapacity ; i-- > 0 ;) {
        for (Entry<K,V> old = (Entry<K,V>)oldMap[i] ; old != null ; ) {
            Entry<K,V> e = old;
            old = old.next;

            int index = (e.hash & 0x7FFFFFFF) % newCapacity;
            e.next = (Entry<K,V>)newMap[index];
            newMap[index] = e;
        }
    }
}

remove方法

public synchronized V remove(Object key) {
    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    @SuppressWarnings("unchecked")
    Entry<K,V> e = (Entry<K,V>)tab[index];
    //遍历Entry链表,e为当前节点,prev为上一个节点
    for(Entry<K,V> prev = null ; e != null ; prev = e, e = e.next) {
        //为什么不直接只用 e.key.equals(key) 来判断,因为e.hash == hash性能更优
        if ((e.hash == hash) && e.key.equals(key)) {
            modCount++;
            if (prev != null) {
                //如果是链表的中间值
                prev.next = e.next;
            } else {
                //如果是链表的第一个
                tab[index] = e.next;
            }
            count--;
            V oldValue = e.value;
            e.value = null;
            return oldValue;
        }
    }
    return null;
}