源碼探究Java_HashMap

1. HashMap 定義,抽取HashMap類中主要變量,以下數組

public class HashMap<K,V> extends AbstractMap<K,V>  implements Map<K,V>, Cloneable, Serializable { 
     /** map中鍵值對的數量 */
     transient int size;
     /** 閥值 (閥值=加載因子*容量),達到後則擴容 */
     int threshold;
    /** 加載因子,默認0.75*/
     final float loadFactor;   
    /** 計算hash值的種子*/
    transient int hashSeed = 0; 
    /**  數組 */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
    /** 鏈表節點定義 */
    static class Entry<K,V> implements Map.Entry<K,V> {
        /** 鍵名 */
        final K key;
        /** 鍵值 */
        V value;
        /** 後繼節點 */
        Entry<K,V> next;
        /** 當前key的hash值 */
        int hash;
    }
}    

2. hash值如何計算函數

    final int hash(Object k) {
        int h = hashSeed;
     /** 字符串hash計算 */
if (0 != h && k instanceof String) { return sun.misc.Hashing.stringHash32((String) k); } h ^= k.hashCode(); /**此函數確保在每一個位位置僅相差常數倍的hashCodes具備有限的衝突數(默認加載因子大約爲8)*/ h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); }

 

3. 在上一步中查看字符串怎麼計算hash值的時候發現HashMap內部的一個惡漢式的單例實現spa

private static class Holder {
  static final JavaLangAccess LANG_ACCESS = SharedSecrets.getJavaLangAccess();
  private Holder() {
   }

   static {
     if(null == LANG_ACCESS) {
        throw new Error("Shared secrets not initialized");
       }
   }
}
相關文章
相關標籤/搜索