1. 程式人生 > >HashTable源碼分析

HashTable源碼分析

mat 否則 returns final 代碼 private bucket detect flag

??本次分析代碼為JDK1.8中HashTable代碼。
??HashTable不允許null作為key和value。
??HashTable中的方法為同步的,所以HashTable是線程安全的。

Entry類

介紹

  • Entry是HashTable內的一個靜態內部類,實現了Map.Entry接口。table的類型就是Entry。

基本參數

  • hash:存這個Entry的hash值
  • key:存key值
  • value:存value的值
  • next:通過鏈表連接下一個Entry
final int hash;
final K key;
V value;
Entry<K,V> next;

構造函數

  • 用來新建Entry,需要四個參數。
protected Entry(int hash, K key, V value, Entry<K,V> next) {
    this.hash = hash;
    this.key =  key;
    this.value = value;
    this.next = next;
}

方法

  • getKey方法:返回key值
  • getValue方法:返回value的值
  • setValue方法:修改value值
  • 重寫了equals和hashCode方法:hashCode方法通過計算該Entry的hash值與value的hash值進行異或運算;equals方法通過判斷key和value是否同時相同來判斷。
public int hashCode() {
    return hash ^ Objects.hashCode(value);
}

public boolean equals(Object o) {
    if (!(o instanceof Map.Entry))
        return false;
    Map.Entry<?,?> e = (Map.Entry<?,?>)o;

    return (key==null ? e.getKey()==null : key.equals(e.getKey())) &&
       (value==null ? e.getValue()==null : value.equals(e.getValue()));
}

HashTable類

繼承與實現

  • HashTable繼承自Dictionary類,實現了Map接口。
public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable

基本參數

  • HashTable中的數據存放在一個叫做table的數組中,類型為Entry,Entry實現了Map.Entry接口,Entry為HashTable的一個靜態內部類。
  • count:entry總數。
  • loadFactor:負載因子。
  • threshold:臨界值,當table的size超過臨界值,就會進行rehash,這個值等於capacity * loadFactor。
    private transient Entry<?,?>[] table;

    private transient int count;

    private int threshold;

    private float loadFactor;

構造函數

  • 默認的HashTable中table的大小為11,負載因子的默認值為0.75。
  • 可以指定初始table的大小,也可以指定loadFactor的大小,也可以將一個Map直接復制到本HashTable。

put方法

  • 同步方法。
  • hash值為key的hashCode。
  • index = (hash & 0x7FFFFFFF) % tab.length,新增的Entry的index值為key的hash值與0x7FFFFFFF求與再對table的長度求余。
  • 獲取到table中下標為index的entry,若存在hash值和key值相同的entry,則用新值替換舊值,若不存在,則新增一個entry。
  • addEntry方法裏,如果count大於等於threshold,則進行rehash,否則新增一個Entry,並將在index位置上的舊的Entry接到新增的Entry後。
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;
}

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

get方法

  • 同步方法。
  • 計算出key的hash值,並計算出table的下標index,然後對該鏈表進行遍歷,若有相同者,則返回value的值,否則返回null。
public synchronized V get(Object key) {
    Entry<?,?> tab[] = table;
    int hash = key.hashCode();
    int index = (hash & 0x7FFFFFFF) % tab.length;
    for (Entry<?,?> e = tab[index] ; e != null ; e = e.next) {
        if ((e.hash == hash) && e.key.equals(key)) {
            return (V)e.value;
        }
    }
    return null;
}

rehash方法

  • 先進行擴容,新的容量為舊的容量的兩倍再加一。
  • 讓table指向容量為新值的新的數組。
  • 將舊的table中原有的值進行重新計算,重新計算出新的index,並將原來table中的鏈表連接到新的table中。
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;
        }
    }
}

hashCode方法

  • 本方法是同步的。
  • 通過計算table中每一個Entry的hashCode之和作為返回值。
public synchronized int hashCode() {
        /*
         * This code detects the recursion caused by computing the hash code
         * of a self-referential hash table and prevents the stack overflow
         * that would otherwise result.  This allows certain 1.1-era
         * applets with self-referential hash tables to work.  This code
         * abuses the loadFactor field to do double-duty as a hashCode
         * in progress flag, so as not to worsen the space performance.
         * A negative load factor indicates that hash code computation is
         * in progress.
         */
        int h = 0;
        if (count == 0 || loadFactor < 0)
            return h;  // Returns zero

        loadFactor = -loadFactor;  // Mark hashCode computation in progress
        Entry<?,?>[] tab = table;
        for (Entry<?,?> entry : tab) {
            while (entry != null) {
                h += entry.hashCode();
                entry = entry.next;
            }
        }

        loadFactor = -loadFactor;  // Mark hashCode computation complete

        return h;
    }

HashTable源碼分析