java之--HashTable

java之--HashTable
===========================================
和HashMap相似,數組+鏈表結構
public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable {
    //The hash table data.
    private transient Entry<K,V>[] table;//數據存儲區

    //The total number of entries in the hash table.
    private transient int count;//table中的數據個數
    
    //The table is rehashed when its size exceeds(超過) this threshold
    //The value of this field is (int)(capacity * loadFactor) capacity爲table的容量
    private int threshold;//擴容閾值
    
    //The load factor for the hashtable
    private float loadFactor;//擴容負載因子

        如果容量table.length=capacity=16,
        負載因子loadFactor=0.75,
        則閾值threshold=16 * 0.75 = 12
        也就是容器中有12個元素的時候,容器開始擴容

    //The number of times this Hashtable has been structurally modified
    private transient int modCount = 0;

    //hashSeed用於計算key的hash值,它與key的hashCode進行按位異或運算。
    //這個hashSeed是一個與實例相關的隨機值,主要用於解決hash衝突。
    transient int hashSeed;

}
初始化:
public Hashtable() {
        this(11, 0.75f);//默認初始容量爲11,負載因子爲0.75
}
public Hashtable(int initialCapacity, float loadFactor) {
    ......
    if (initialCapacity==0)
        initialCapacity = 1;
    this.loadFactor = loadFactor;//負載因子
    table = new Entry[initialCapacity];//初始化table
    threshold = (int)Math.min(initialCapacity * loadFactor, MAX_ARRAY_SIZE + 1);//計算閥值
    initHashSeedAsNeeded(initialCapacity);//初始化HashSeed值
}
1.put()添加元素
public synchronized V put(K key, V value) {
        // Make sure the value is not null
        if (value == null) {//value不能爲空
            throw new NullPointerException();
        }

        // Makes sure the key is not already in the hashtable.
        Entry tab[] = table;
        int hash = hash(key);
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<K,V> e = tab[index] ; e != null ; e = e.next) {
            if ((e.hash == hash) && e.key.equals(key)) {
                V old = e.value;
                e.value = value;//有重複的key,新value會覆蓋原來的
                return old;
            }
        }

        modCount++;
        if (count >= threshold) {
            // Rehash the table if the threshold is exceeded
            rehash();//擴容

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

        // Creates the new entry.
        Entry<K,V> e = tab[index];
    //如果有碰撞,hash衝突,新添加的元素放在鏈頭,原來的元素爲新添加元素的next
        tab[index] = new Entry<>(hash, key, value, e);
        count++;
        return null;
}

Entry節點:

private static class Entry<K,V> implements Map.Entry<K,V> {

        int hash;
        final K key;
        V value;
        Entry<K,V> next;
}
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//擴容
protected void rehash() {
        int oldCapacity = table.length;
        Entry<K,V>[] oldMap = table;

        // overflow-conscious code
        int newCapacity = (oldCapacity << 1) + 1;//新容量爲oldCapacity*2 + 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<K,V>[] newMap = new Entry[newCapacity];

        modCount++;
        threshold = (int)Math.min(newCapacity * loadFactor, MAX_ARRAY_SIZE + 1);
        boolean rehash = initHashSeedAsNeeded(newCapacity);

        table = newMap;
        //容量增加後,重新調整元素位置
        for (int i = oldCapacity ; i-- > 0 ;) {//桶(數組)
            for (Entry<K,V> old = oldMap[i] ; old != null ; ) {//鏈(鏈表)
                Entry<K,V> e = old;
                old = old.next;

                if (rehash) {
                    e.hash = hash(e.key);
                }
                int index = (e.hash & 0x7FFFFFFF) % newCapacity;
                e.next = newMap[index];
                newMap[index] = e;
            }
        }
}
2.remove()刪除元素
public synchronized V remove(Object key) {
        Entry tab[] = table;
        int hash = hash(key);
        int index = (hash & 0x7FFFFFFF) % tab.length;
        for (Entry<K,V> e = tab[index], prev = null ; e != null ; prev = e, e = e.next) {
            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;
    }
HashTable與HashMap不同點:
public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, Serializable {
public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable {
1.HashMap是非synchronized,而HashTable是synchronized
HashMap:public V put(K key, V value) {}
HashTable:public synchronized V put(K key, V value) {}

2.HashMap可以接受爲null的鍵(key)和值(value),HashTable鍵值都不能爲null
HashMap:
public V put(K key, V value) {
        ......
        if (key == null)
            return putForNullKey(value);//放在table[0]或其鏈上
}
HashMap中只有一條記錄可以是一個空的key(多個時,新value會覆蓋原來的),
但任意數量的條目可以是空的value。

HashTable:
public synchronized V put(K key, V value) {
        // Make sure the value is not null
    if (value == null) {
            throw new NullPointerException();
        }
    int hash = hash(key);
    ......
}
private int hash(Object k) {
    return hashSeed ^ k.hashCode();//key=k爲null,這裏會報NullPointerException
}
HashTable的key、value都不能爲空


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章