天天看點

Java集合類架構學習 4.2 —— HashMap(JDK1.7)

看完1.6的,接下來看下1.7的,改動并不多,稍微過下就行

零、主要改動 相對于1.6: 1、懶初始化 lazy init,預設構造的HashMap底層數組并不會直接初始化,而是先使用空數組,等到實際要添加資料時再真正初始化。 2、引入hashSeed,用于得到更好的hash值,以及在擴容時判斷是否需要重新計算每個Entry的hash值(Entry的hash不再是final的,可以變了)。 3、修複1.6的一些小問題,加上其他的一些小改動。 大的方面沒什麼改動。

一、基本性質 和1.6的一樣。 整體結構和1.6的一緻。

二、常量和變量 1、常量 變化比較少,多的兩個常量對HashMap的基本實作基本沒什麼影響。

static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
static final int MAXIMUM_CAPACITY = 1 << 30;
static final float DEFAULT_LOAD_FACTOR = 0.75f;

/** An empty table instance to share when the table is not inflated. */
static final Entry<?,?>[] EMPTY_TABLE = {}; // 懶初始化使用的空數組,

// 一個預設門檻值。高于該值,且以String作為Key時,使用備用哈希hash函數(sun.misc.Hashing.stringHash32),這個備用hash函數能減少String的hash沖突。
// 此值是最大int型,表明hash表再也不能擴容了,繼續put下去,hash沖突會越來越多。
// 至于為什麼是String型才有這種特殊待遇,因為String是最常見的Key的類型。Integer雖然也很常見,但是Integer有範圍限制,并且它的hashCode設計得就非常好(就是自身的數值)。
// 可以通過定義系統屬性jdk.map.althashing.threshold來覆寫這個值。
// 值為1時,總是會對String類型的key使用備用的hash函數;值為-1,則一定不使用備用hash函數。
static final int ALTERNATIVE_HASHING_THRESHOLD_DEFAULT = Integer.MAX_VALUE;
           

2、變量 基本沒啥大的變化。

/** The table, resized as necessary. Length MUST Always be a power of two. */
transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE; // 懶初始化,是以給一個空數組 ,其實空數組也沒什麼用,用null也行

transient int size;
final float loadFactor;
transient int modCount;

// 通常的擴容門檻值,另外在懶初始化中,真正初始化時會使用這個值作為第一次的容量
int threshold;

// 一個hash種子,用于參與hash函數中的運算,獲得更好的hash值來減少hash沖突
// 值為0時會禁止掉備用hash函數
transient int hashSeed = 0;

private transient Set<Map.Entry<K,V>> entrySet = null;
// keySet values繼承使用AbstractMap的父類的屬性
           

三、基本類

// Entry就一個變化,hash值不再是final的
static class Entry<K,V> implements Map.Entry<K,V> {
    final K key;
    V value;
    Entry<K,V> next;
    int hash; // 就這一個改變,hash不再是final的,擴容時可以重新計算hash值

    // 後面的跟1.6的一樣,不說了
}

/** holds values which can't be initialized until after VM is booted.  */
// 這個類就是用來持有 ALTERNATIVE_HASHING_THRESHOLD的,影響String在極端情況下的hash值的計算,不影響HashMap基本的實作
private static class Holder {

    /**  Table capacity above which to switch to use alternative hashing. */
    static final int ALTERNATIVE_HASHING_THRESHOLD;

    static {
        String altThreshold = java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction( "jdk.map.althashing.threshold")); 

        int threshold;
        try {
            threshold = (null != altThreshold) ? Integer.parseInt(altThreshold) : ALTERNATIVE_HASHING_THRESHOLD_DEFAULT;

            // disable alternative hashing if -1
            if (threshold == -1) {
                threshold = Integer.MAX_VALUE;
            }

            if (threshold < 0) {
                throw new IllegalArgumentException("value must be positive integer.");
            }
        } catch(IllegalArgumentException failed) {
            throw new Error("Illegal value for 'jdk.map.althashing.threshold'", failed);
        }

        ALTERNATIVE_HASHING_THRESHOLD = threshold;
    }
}
           

四、構造方法 主要是針對懶初始化的改動,比較簡單,也沒什麼好說的。

public HashMap(int initialCapacity, float loadFactor) {
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
    if (initialCapacity > MAXIMUM_CAPACITY)
        initialCapacity = MAXIMUM_CAPACITY;
    if (loadFactor <= 0 || Float.isNaN(loadFactor))
        throw new IllegalArgumentException("Illegal load factor: " + loadFactor);

    this.loadFactor = loadFactor;
    threshold = initialCapacity; // 初始容量儲存在threshold中,真正初始化後threshold才是門檻值
    init(); // 這個方法什麼也沒做
    // 初始化後數組table是預設值空數組,沒有真正進行初始化
}

public HashMap(int initialCapacity) {
    this(initialCapacity, DEFAULT_LOAD_FACTOR);
}

public HashMap() {
    this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR);
}

// loadFactor使用預設值0.75f,因為m是接口類型,可能沒有loadFactor這個屬性
public HashMap(Map<? extends K, ? extends V> m) {
    this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR);
    inflateTable(threshold);

    putAllForCreate(m);
}
           

下面是真正的初始化的相關代碼。

// 使用比較高大上的算法求不小于number的滿足2^n的數
private static int roundUpToPowerOf2(int number) {
    // assert number >= 0 : "number must be non-negative";
    return number >= MAXIMUM_CAPACITY
            ? MAXIMUM_CAPACITY
            : (number > 1) ? Integer.highestOneBit((number - 1) << 1) : 1;
}

// 真正初始化HashMap
private void inflateTable(int toSize) {
    // Find a power of 2 >= toSize
    int capacity = roundUpToPowerOf2(toSize);

    threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1);
    table = new Entry[capacity];
    initHashSeedAsNeeded(capacity);
}

// 初始化hash種子
// hashseed相關的可以不用了解太多,它隻影響hash值的生成,以及擴容時是否需要重新計算hash值(rehash),本身對HashMap的基本的實作沒影響
final boolean initHashSeedAsNeeded(int capacity) {
    boolean currentAltHashing = hashSeed != 0;
    boolean useAltHashing = sun.misc.VM.isBooted() && (capacity >= Holder.ALTERNATIVE_HASHING_THRESHOLD);
    boolean switching = currentAltHashing ^ useAltHashing;
    if (switching) {
        hashSeed = useAltHashing ? sun.misc.Hashing.randomHashSeed(this) : 0;
    }
    return switching;
}
           

五、一些内部方法 這部分基本沒變。

// 多了個hashSeed,以及對String的特别處理
// null 依然視為hash = 0,總是放在index = 0的hash桶中
final int hash(Object k) {
    int h = hashSeed;
    if (0 != h && k instanceof String) {
        return sun.misc.Hashing.stringHash32((String) k);
    }

    h ^= k.hashCode();

    // This function ensures that hashCodes that differ only by
    // constant multiples at each bit position have a bounded
    // number of collisions (approximately 8 at default load factor).
    h ^= (h >>> 20) ^ (h >>> 12);
    return h ^ (h >>> 7) ^ (h >>> 4);
}

static int indexFor(int h, int length) {
    // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
    return h & (length-1);
}
           

六、擴容

// resize 修複了threshold過早地變為Integer.MAX_VALUE的問題,其餘跟1.6一緻
void resize(int newCapacity) {
    Entry[] oldTable = table;
    int oldCapacity = oldTable.length;
    if (oldCapacity == MAXIMUM_CAPACITY) { // 此時數組才是真正不能擴容了
        threshold = Integer.MAX_VALUE;
        return;
    }

    Entry[] newTable = new Entry[newCapacity];
    transfer(newTable, initHashSeedAsNeeded(newCapacity));
    table = newTable;
    threshold = (int)Math.min(newCapacity * loadFactor, MAXIMUM_CAPACITY + 1);
    // 上面這行代碼,可以避免1.6可能發生的因為newCapacity * LoadFacotr大于Integer.MAX_VALUE,導緻後續本來還可以擴容,但是無法進入resize方法的問題
}

// 多一個真正的rehash的判斷,其餘跟1.6的一緻
void transfer(Entry[] newTable, boolean rehash) {
    int newCapacity = newTable.length;
    for (Entry<K,V> e : table) {
        while(null != e) {
            Entry<K,V> next = e.next;
            if (rehash) { // 為true就要進行真正的rehash
                e.hash = null == e.key ? 0 : hash(e.key);
            }
            int i = indexFor(e.hash, newCapacity);
            e.next = newTable[i];
            newTable[i] = e;
            e = next;
        }
    }
}
           

七、常用方法 1、讀操作 跟1.6的基本一樣,但還是貼一下代碼。

public int size() {
    return size;
}

public boolean isEmpty() {
    return size == 0;
}

public V get(Object key) {
    if (key == null)
        return getForNullKey();
    Entry<K,V> entry = getEntry(key);

    return null == entry ? null : entry.getValue();
}

private V getForNullKey() {
    if (size == 0) {
        return null;
    }
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null)
            return e.value;
    }
    return null;
}

public boolean containsKey(Object key) {
    return getEntry(key) != null;
}

final Entry<K,V> getEntry(Object key) {
    if (size == 0) {
        return null;
    }

    int hash = (key == null) ? 0 : hash(key);
    for (Entry<K,V> e = table[indexFor(hash, table.length)];
         e != null;
         e = e.next) {
        Object k;
        if (e.hash == hash &&
            ((k = e.key) == key || (key != null && key.equals(k))))
            return e;
    }
    return null;
}

public boolean containsValue(Object value) {
    if (value == null)
        return containsNullValue();

    Entry[] tab = table;
    for (int i = 0; i < tab.length ; i++)
        for (Entry e = tab[i] ; e != null ; e = e.next)
            if (value.equals(e.value))
                return true;
    return false;
}

private boolean containsNullValue() {
    Entry[] tab = table;
    for (int i = 0; i < tab.length ; i++)
        for (Entry e = tab[i] ; e != null ; e = e.next)
            if (e.value == null)
                return true;
    return false;
}
           

2、寫操作 除了懶加載導緻put/remove的判斷多了些外,變化的地方就是添加節點觸發擴容那裡變了,注釋上寫了。

public V put(K key, V value) {
    if (table == EMPTY_TABLE) { // 考慮還未真正初始化的情況
        inflateTable(threshold);
    }
    if (key == null)
        return putForNullKey(value);
    int hash = hash(key);
    int i = indexFor(hash, table.length);
    for (Entry<K,V> e = table[i]; e != null; e = e.next) {
        Object k;
        if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }

    modCount++;
    addEntry(hash, key, value, i);
    return null;
}

private V putForNullKey(V value) {
    for (Entry<K,V> e = table[0]; e != null; e = e.next) {
        if (e.key == null) {
            V oldValue = e.value;
            e.value = value;
            e.recordAccess(this);
            return oldValue;
        }
    }
    modCount++;
    addEntry(0, null, value, 0);
    return null;
}

// 這個跟1.6有些差別
// 1、走實用主義,擴容多了個條件。當添加的節點是hash桶的第一個節點時,一定不擴容,是以會出現size > threshold的情況。
// 2、幾步的操作順序不一樣。jdk1.6的是先把節點添加到連結清單中,再判斷是否擴容;1.7這裡是先判斷是否擴容,擴容完再把節點添加到連結清單中。
void addEntry(int hash, K key, V value, int bucketIndex) {
    if ((size >= threshold) && (null != table[bucketIndex])) {
        resize(2 * table.length);
        hash = (null != key) ? hash(key) : 0;
        bucketIndex = indexFor(hash, table.length);
    }

    createEntry(hash, key, value, bucketIndex);
}

void createEntry(int hash, K key, V value, int bucketIndex) {
    Entry<K,V> e = table[bucketIndex];
    table[bucketIndex] = new Entry<>(hash, key, value, e);
    size++;
}

public void putAll(Map<? extends K, ? extends V> m) {
    int numKeysToBeAdded = m.size();
    if (numKeysToBeAdded == 0)
        return;

    if (table == EMPTY_TABLE) { // 考慮還未真正初始化的情況
        inflateTable((int) Math.max(numKeysToBeAdded * loadFactor, threshold));
    }

    // 跟1.6的一樣,稍微保守些,多判斷下
    if (numKeysToBeAdded > threshold) {
        int targetCapacity = (int)(numKeysToBeAdded / loadFactor + 1);
        if (targetCapacity > MAXIMUM_CAPACITY)
            targetCapacity = MAXIMUM_CAPACITY;
        int newCapacity = table.length;
        while (newCapacity < targetCapacity)
            newCapacity <<= 1;
        if (newCapacity > table.length)
            resize(newCapacity);
    }

    for (Map.Entry<? extends K, ? extends V> e : m.entrySet())
        put(e.getKey(), e.getValue());
}

public V remove(Object key) {
    Entry<K,V> e = removeEntryForKey(key);
    return (e == null ? null : e.value);
}

final Entry<K,V> removeEntryForKey(Object key) {
    if (size == 0) { // 考慮還未真正初始化的情況
        return null;
    }
    int hash = (key == null) ? 0 : hash(key);
    int i = indexFor(hash, table.length);
    Entry<K,V> prev = table[i];
    Entry<K,V> e = prev;

    while (e != null) {
        Entry<K,V> next = e.next;
        Object k;
        if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k)))) {
            modCount++;
            size--;
            if (prev == e)
                table[i] = next;
            else
                prev.next = next;
            e.recordRemoval(this);
            return e;
        }
        prev = e;
        e = next;
    }

    return e;
}

public void clear() {
    modCount++;
    Arrays.fill(table, null); // 就是循環指派
    size = 0;
}
           

八、視圖和疊代器 跟1.6的一樣。

1.7相對1.6,改動不大,基本上沒啥太重要的改動。了解1.6的之後,稍微過下1.7的就行。 接下來看下1.8的,相對來說就是比較大的改動了。