HashMap從懵懂到熟悉

什麼是Hashmap

HashMap就是一個容器,用來存儲數據,但是爲什麼不使用Arraylist,或者爲什麼不使用Link

數組的形式
在這裏插入圖片描述
link的形式
在這裏插入圖片描述
hashMap的形式
在這裏插入圖片描述
看到這裏是不是有一種恍然大悟的感覺,hashMap其實就是數組加鏈表,我最開始的時候問過爲什麼不使用數組,
數組:使用數組你會發現他查詢很快,但是增刪改查效率非常低
鏈表:鏈表是非常快,但是對於增傷改查非常快,如果查詢數組最好,並且鏈表非常消耗資源
Hashmap:而Hashmap出現就是結合了他們兩個的優點※

提問問題

如果你把我下面的問題都會了,那說明你還不錯哦,嘿嘿

  • 1爲什麼使用hashcode?
  • 2爲什麼會有數組,爲什麼用鏈表?
  • 3什麼時候擴容,如果進行擴容?
  • 4什麼時候使用使用紅黑樹?
  • 5爲什麼hashcode要和節點進行與操作?
  • 6數組長度多少,其他空間不可以佔用,除非擴容?
  • 7爲什麼判斷hash和可以是否相等?
  • 8整個體系的流程是什麼?

代碼

一般情況下我們都是這樣使用HashMap

  public static void main(String[] args){
        HashMap<String,String> hashMap = new HashMap<>();
        hashMap.put("judy","6688");
        String judy = hashMap.get("judy");
        System.out.println(judy);
    }

源碼分析

爲什麼使用HashCode

你有沒有想過一個問題,如果我們使用hashMap,我們的下角標是如何生成的,難道我們使用的是隨機數生成的下角標嗎?那誰知道數據長度得有多大啊,

  1. 得到一個節點,重點看hash(key)
  public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
  1. 你會發現hashCode會與做與運行把低16位於高16位進行異或運算,爲什麼會這麼做呢,這麼做的時候我們會把前16給取出轉換爲二進制與h進行異或運算,這樣就避免了出現重複的值,如果出現重複的值,可能會出現其中一個鏈表很長,但是其他位置根本沒有數據,所以要把其他的位置都用起來.

下面的操作就是計算node節點到底在數組的什麼位置?
n-1 & hash =====>hash%n , 得到的是0-15的區間, n的默認大小是16
0010101011001010010100101001
01111
最終的結果肯定是在16範圍之內的.爲什麼用與是因爲&與操作效率比較高

   if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);

3通過第二步的操作大家有沒有感到疑惑,如果是第2步操作得到的是15,那麼這個時候二進制變爲01110,這個時候不滿足16,導致分佈不勻均,那麼如果才能分佈均勻,所以數組的大家都是2的n次冪

在最開始的時候我們就給定默認的值,所以這裏的16是有原因的,與操作的時候纔會分佈均勻

    /**
     * The default initial capacity - MUST be a power of two.
     */
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16

當看到這個的時候你想到了什麼,我最開始的時候說要使用hashCode,而hashCode也就是從整個地方過來的,但是你有沒有發現當拿到key的hashCode的誰還會進行16位的與操作,爲什麼在找數組下標(與操作)之前會使用hashCode在進行本身的異或?

原因就是爲了避免出現重複的數據,爲了node在數組中的位置分佈均勻才做的這個操作

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

讓他們兩個之間進行異或,得到最後的hashcode
0101001010010高16位
0101001001001低16位

初始化數組

在這裏只是聲明瞭數組,但是並沒有給數組賦值

    /**
     * The table, initialized on first use, and resized as
     * necessary. When allocated, length is always a power of two.
     * (We also tolerate length zero in some operations to allow
     * bootstrapping mechanics that are currently not needed.)
     */
    transient Node<K,V>[] table;

賦值語句

  if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
//這個方法是判斷是否需要初始化
 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        int oldThr = threshold;
        int newCap, newThr = 0;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
   static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
  //這句話纔是關鍵,所以默認賦給的值就是16,從最開始見解爲什麼長度必須是2N次冪到現在初值爲16,大家應該理解了吧
  newCap = DEFAULT_INITIAL_CAPACITY;
  newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
  
  //並且最後把值給了threshold
  threshold = newThr;

把數據放到指定位置

如果是第一次存放

  if ((p = tab[i = (n - 1) & hash]) == null)
  tab[i] = newNode(hash, key, value, null);

如果是key和hash相等,所以你會發現他到最後返回的以前的value

 if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;

//返回以前的value
   if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }

如果使用紅黑樹

  else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);

如果是在鏈表裏
這個時候你會發現他其實就是循環鏈表,然後判斷是否爲空

         for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }

如果這個時候鏈表的長度超出我們設置的鏈表長度8-1,那麼這個時候就分配紅黑樹

    static final int TREEIFY_THRESHOLD = 8;

什麼時候擴容

看到這的時候大家有沒有疑問,有沒有想過數組長度只讓用到75%,那麼他怎麼知道是不是需要擴容呢?

// 這塊代碼記錄數組已經被佔用了多少
      //修改的次數
        ++modCount;
        //size表示鍵值的數量//threshold表示容量
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;

當他的size大於了threshold就會進行擴容,執行resize()操作,最開始我們進行數組初始化的時候也是執行的resize()操作

初始化或加倍表格大小。, 如果爲null,則分配*符合字段閾值中保存的初始容量目標。 

否則,因爲我們使用的是2次冪擴展,所以每個bin中的*元素必須保持相同的索引,或者在新表中以2的偏移量移動*

他首先會判斷你是否大於0 ,如果大於0,再判斷是否大於最大值

 if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            //--------------------------擴容操作--------------
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold
        }
        //----------------------移動---當前地址加上原來容量的位置----------
     if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
    /**
     * The maximum capacity, used if a higher value is implicitly specified
     * by either of the constructors with arguments.
     * MUST be a power of two <= 1<<30.
     */
    static final int MAXIMUM_CAPACITY = 1 << 30;

鏈表可以無限的伸展嗎

你有沒有想過這個問題? 假如hashmap的其中有一個位一直有node,那麼這個時候會無限的向鏈表中添加數據,那麼這個時候鏈表的數據就會變得很長,所以非常不好, 解決方案是設置規定的值

鏈表的長度不可以超過8

    /**
     * The bin count threshold for using a tree rather than list for a
     * bin.  Bins are converted to trees when adding an element to a
     * bin with at least this many nodes. The value must be greater
     * than 2 and should be at least 8 to mesh with assumptions in
     * tree removal about conversion back to plain bins upon
     * shrinkage.
     */
    static final int TREEIFY_THRESHOLD = 8;

總結

好吧,下一步就是手寫了…加油judy, 總歸還是得感謝徐 X X ,❥(^_-)

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