【Java集合類】HashMap源碼淺析(一)

參考鏈接

  1. https://blog.csdn.net/tuke_tuke/article/details/51588156

HashMap的繼承關係

在這裏插入圖片描述

HashMap的核心數據結構

一些默認值: table默認容量爲2^4 =16,最大容量爲2^30, load factor 爲0.75f

結構示意圖
HashMap的核心數據結構可以看成是數組+鏈表的結合體

table是數組,數組元素是Node類型,node節點有指向下一個node節點的指針(實際上是Java中的引用),從而構成鏈表。

結構變化:當單個桶中的node大於等於8時,考慮是否將結構轉變爲紅黑樹(滿足table.length>64),不然的話table擴容兩倍。node鏈表長度小於6時,考慮解開樹結構。

爲何發生結構轉變,因爲紅黑樹的查找效率爲O(logn),而鏈表的查找效率爲O(n)

在這裏插入圖片描述

/**
	Objects中的hashcode

     * Returns the hash code of a non-{@code null} argument and 0 for
     * a {@code null} argument.
     */
    public static int hashCode(Object o) {
        return o != null ? o.hashCode() : 0;
    }
//object 中的hashcode
 public native int hashCode();

HashMap核心的數據結構

  /**
     * Basic hash bin node, used for most entries.  (See below for
     * TreeNode subclass, and in LinkedHashMap for its Entry subclass.)
     */
 static class Node<K,V> implements Map.Entry<K,V> {
        final int hash;
        final K key;
        V value;
        Node<K,V> next;

        Node(int hash, K key, V value, Node<K,V> next) {
            this.hash = hash;
            this.key = key;
            this.value = value;
            this.next = next;
        }

        public final K getKey()        { return key; }
        public final V getValue()      { return value; }
        public final String toString() { return key + "=" + value; }

		// jdk 1.8中, hash值是key和value的hashcode的異或
        public final int hashCode() {
            return Objects.hashCode(key) ^ Objects.hashCode(value);
        }

        public final V setValue(V newValue) {
            V oldValue = value;
            value = newValue;
            return oldValue;
        }

		
        public final boolean equals(Object o) {
        	//  如果是同一個實例對象
            if (o == this)
                return true;
             // 比較的對象是Map.Entry的實例或者子類實例,在key和value都相等的情況下才相等
            if (o instanceof Map.Entry) {
                Map.Entry<?,?> e = (Map.Entry<?,?>)o;
                if (Objects.equals(key, e.getKey()) &&
                    Objects.equals(value, e.getValue()))
                    return true;
            }
            return false;
        }
    }
/**
     * Entry for Tree bins. Extends LinkedHashMap.Entry (which in turn
     * extends Node) so can be used as extension of either regular or
     * linked node.
     */
    static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

        /**
         * Returns root of tree containing this node.
         */
        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }

get操作

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }

    /**
     * Implements Map.get and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @return the node, or null if none
     */
    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; 
        Node<K,V> first, e; 
        int n; 
        K k;
        // first = tab[(n - 1) & hash] 找到key值的hash值在table中對應的位置
        if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // always check first node
                ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {  // 遍歷檢查接下來的節點
                if (first instanceof TreeNode)
                    return ((TreeNode<K,V>)first).getTreeNode(hash, key);
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        return e;
                } while ((e = e.next) != null);
            }
        }
        return null;
    }

步驟描述:

  1. get(key)方法時獲取key的hash值,計算hash&(n-1)得到在鏈表數組中的位置,first=tab[hash&(n-1)],
  2. 再判斷first的key是否與參數key相等,不等就遍歷後面的鏈表找到相同的key值返回對應的Value值即可

put操作


 // 返回值V 與鍵關聯的前一個值,如果沒有鍵的映射,則爲null。
 //(null返回也可以指示以前將null與鍵關聯的映射。)與鍵關聯的前一個值,如果沒有鍵的映射,則爲null。
 //(null返回也可以指示以前將null與鍵關聯的映射。)
 public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

    /**
     * Implements Map.put and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to put
     * @param onlyIfAbsent if true, don't change existing value
     * @param evict if false, the table is in creation mode.
     * @return previous value, or null if none
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; 
        Node<K,V> p; 
        int n, i;
        
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
         //根據鍵值key計算hash值得到插入的數組索引i,如果當前位置爲空直接插入,p爲該位置上第一個節點
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
        	// 處理衝突
            Node<K,V> e;
            K k;
        	// 在hash值相同的情況下,第一個節點的key和被put的key相同,原來鍵值對被替換
        	// e是插入node的前一個值
            if (p.hash == hash && ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode) // p樹節點
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            	// 解決鏈表衝突
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                    	// 新增一個node,直接掛後面
                        p.next = newNode(hash, key, value, null);
                        //如果衝突的節點數已經達到8個,看是否需要改變衝突節點的存儲結構
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        	//tab.length > 64 才進行樹化(樹化衝突的部分),否則只是進行2倍擴容
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash && ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;
    }

步驟描述:

  1. 判斷鍵值對數組 tab[] 是否爲空或爲null,否則以默認大小resize();
  2. 根據鍵值key計算hash值得到插入的數組索引i,如果tab[i]==null,直接新建節點添加,否則轉入3
  3. 判斷當前數組中處理hash衝突的方式爲鏈表還是紅黑樹(check第一個節點類型即可),分別處理

resize() 擴容操作

 /**
     * Initializes or doubles table size.  If null, allocates in
     * accord with initial capacity target held in field threshold.
     * Otherwise, because we are using power-of-two expansion, the
     * elements from each bin must either stay at same index, or move
     * with a power of two offset in the new table.
     *
     * @return the table
     */
    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);
        }
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
            Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
        table = newTab;
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) {
                Node<K,V> e;
                if ((e = oldTab[j]) != null) {
                    oldTab[j] = null;
                    if (e.next == null)
                        newTab[e.hash & (newCap - 1)] = e;
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // preserve order
                        Node<K,V> loHead = null, loTail = null;
                        Node<K,V> hiHead = null, hiTail = null;
                        Node<K,V> next;
                        do {
                            next = e.next;
                            if ((e.hash & oldCap) == 0) {
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

構造hash表時,如果不指明初始大小,默認大小爲16(即Node數組大小16),如果Node[]數組中的元素達到(填充比*Node.length)重新調整HashMap大小 變爲原來2倍大小

總結

HashMap中,key的hashcode方法和equal方法需要用戶自己進行重寫。因爲在put過程中,key.hashcode() 決定了node在table中的位置。key的equal方法決定了node在鏈表或者是紅黑樹中的位置。

和HashTable的比較:
相同點:
實現原理相同,功能相同,底層都是哈希表結構,查詢速度快,在很多情況下可以互用

不同點:
1、Hashtable是早期提供的接口,HashMap是新版JDK提供的接口。
2、Hashtable繼承Dictionary類,HashMap實現Map接口。
3、Hashtable線程安全,HashMap線程非安全。
4、Hashtable不允許null值,HashMap允許null值。

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