JDK 7 HashMap原理解讀

存儲原理

數組是最基本的數據結構,ArrayList內部就是數組實現的,下標定位位置,然後在數組下標位置存放元素,每添加一個元素,下標就+1,map和list有一點相似,就是內部也有個數組, 它通過key存放獲取對象,以key計算數組下標。使用hashCode的話,得出的值很大,很容易是數組越界,可以使用取餘的方式減小這個,那麼餘多少呢?比如下標是0-7,那麼我們可以餘它的數組大小(length),hashCode是隨機的,得出的下標也是隨機的,這也使得數組下標隨機平均。
在這裏插入圖片描述

但還有一個問題,hashCode是隨機的,但在取餘之後得到的值很可能是相同的,比如第一次你存了kk1: vv1,第二次存放kk2: vv2計算key後得出的位置也是同一個位置,那麼在同一下標有兩個對象了,那麼可以鏈表去解決這個問題;再來一個,也是計算得到同一個下標,考慮一個問題,是插入頭部比較快還是尾部比較快?
如果是頭插法,只需要修改新節點的next的下一個節點指針就行了,而如果是尾插,那麼還需要遍歷鏈表,然後修改尾部的指針,顯然,尾插法的效率不是很高,map裏就是用的頭插法,頭插法只有next的元素,這是查找下一個元素使用的,它沒有向上查找的方式,它的查找方式也是先計算數組下標,得到下標後,找到對應的鏈表,然後遍歷的:
在這裏插入圖片描述
上面只是對map的一個原理說明,並不嚴謹。

源碼解析

這裏從HashMap的源碼上去看HashMap這個結構,從源碼分析理解。

HashMap裏有這些個屬性:

	// 默認初始容量 16
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
	// 最大容量
    static final int MAXIMUM_CAPACITY = 1 << 30;
	// 默認加載因子
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
	// 空數組對象
    static final Entry<?,?>[] EMPTY_TABLE = {};
	// 內部數組,
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;
	// map長度
    transient int size;
	// 閾值,是否擴容根據這個判斷:threshold = (int) Math.min(capacity * loadFactor, MAXIMUM_CAPACITY + 1) => capacity * loadFactor
    int threshold;
	// 加載因子,擴容計算用到
    final float loadFactor;
	// 修改計數
    transient int modCount;
	// hash種子,計算hash值用到,爲了是計算的hashCode更加的散列隨機。
	transient int hashSeed = 0;

Entry<K,V>[] 的定義裏有這麼幾個屬性,只有next,沒有向前查找的對象,所以遍歷,只能從頭往下遍歷。

final K key;
V value;
// 指向下一個對象
Entry<K,V> next;
int hash;

構造行數從put方法開始看:

public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }
    // key == null 的情況
        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;
    }

put方法一進來就是這個,初始化內部數組

 if (table == EMPTY_TABLE) {
            inflateTable(threshold);
        }

進入inflateTable方法,首先它有一個計算容量的方法roundUpToPowerOf2,然後計算閾值threshold,然後是計算哈希種子。

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

跟進:

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

上面這一串就需要看:

 Integer.highestOneBit((number - 1) << 1)
 public static int highestOneBit(int i) {
        // HD, Figure 3-1
        i |= (i >>  1);
        i |= (i >>  2);
        i |= (i >>  4);
        i |= (i >>  8);
        i |= (i >> 16);
        return i - (i >>> 1);
    }

這個是計算小於等於當前值的二次方數,比如下面給定值爲17,其結果是16,給定值是18,19,20都會是16,

i=17 =>
0000 0000 0000 0000 0000 0000 0001 0001

(i >> 1) =>
0000 0000 0000 0000 0000 0000 0000 1000

i |= (i >> 1) =>
0000 0000 0000 0000 0000 0000 0001 1000

i |= (i >> 16) =>
0000 0000 0000 0000 0000 0000 0001 1111

i - (i >>> 1) =>
0000 0000 0000 0000 0000 0000 0001 1111
0000 0000 0000 0000 0000 0000 0000 1111
0000 0000 0000 0000 0000 0000 0001 0000

roundUpToPowerOf2註釋寫着要2的每次方數,那爲什麼要2的冪次方數呢?

可以看看這篇博客: https://blog.csdn.net/LLF_1241352445/article/details/81321991?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.nonecase

其結論就是:用位運算取餘,還有就是計算出的數組下標更加散列平均。

瞭解了highestOneBit方法後,再看上一層代碼,爲什麼要-1,和左移1位?

 Integer.highestOneBit((number - 1) << 1)

原因是

  • 我們要得到的是一個大於等於在給定值的一個2的冪次方數,highestOneBit得到的是一個小於等於給定值的冪次方數,所以左移1位;假如我們給定值爲17,那麼要得到的結果應該是32,如果我們不左移,最後得到的值肯定是16
  • 假如給定值是16,要得到結果應該是16,左移1位得到32,所以左移前-1得到15,在左移得到30才能得到16

返回put方法有一段:

  if (key == null)
            return putForNullKey(value);
 private V putForNullKey(V value) {
     // 遍歷內部數組的第0個位置的鏈表,查找是否有key == null的鍵,如果有就返回舊值
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                // 這個方法不管他,跟hashMap沒有關係,這個是給它子類(LinkedHashMap)寫的。
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }

再回到put方法:

public V put(K key, V value) {
        if (table == EMPTY_TABLE) {
            // 初始化數組
            inflateTable(threshold);
        }
    // 第一種情況key == null
        if (key == null)
            return putForNullKey(value);
    // 計算hash值
        int hash = hash(key);
    // 這裏就是hash & (table.length - 1)
    // 計算數組下標
        int i = indexFor(hash, table.length);
    // 遍歷數組下標對應的鏈表
        for (Entry<K,V> e = table[i]; e != null; e = e.next) {
            Object k;
            // 判斷key計算的hash值相同,且key值相同
            if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
                // 設置新值,獲取舊值並返回
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
		// 每次修改+1
        modCount++;
    // 如果沒有找的對應的,就新增一個
        addEntry(hash, key, value, i);
        return null;
    }

modCount這個標識是一種快速失敗的機制,可以這樣理解,多線程下,一個線程在遍歷,一個線程在新增或刪除,遍歷了一般,元素被刪除了,在遍歷的時候就會出現問題,取值、個數都不對了,所以必須拋一個異常結束這個錯誤操作。

  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 transfer(Entry[] newTable, boolean rehash) {
        int newCapacity = newTable.length;
     // 遍歷就數組
        for (Entry<K,V> e : table) {
            // 遍歷每一個元素下的鏈表
            while(null != e) {
                Entry<K,V> next = e.next;
                // 重新計算hash值
                if (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;
            }
        }
    }

而get方法相對簡單些

 public V get(Object key) {
        if (key == null)
            // 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) {
            // 找到key == null 的元素並返回
            if (e.key == null)
                return e.value;
        }
        return 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;
            // 判斷hash值、key相同並返回
            if (e.hash == hash &&
                ((k = e.key) == key || (key != null && key.equals(k))))
                return e;
        }
        return null;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章