HashMap原始碼分析,未完待續

J_W發表於2018-12-09

hashmap是一個Node的陣列,以下為原始碼分析: 陣列大小是而2的冪,初始大小16:

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

如果傳入的構造引數不是2的冪,以下方法取該數字的下一個2的冪。通過無符號右移和或運算,讓每一個二進位制位都變成1,

     /**
     * Returns a power of two size for the given target capacity.
     */
    static final int tableSizeFor(int cap) {
        int n = cap - 1;
        n |= n >>> 1;
        n |= n >>> 2;
        n |= n >>> 4;
        n |= n >>> 8;
        n |= n >>> 16;
        return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
    }
複製程式碼

陣列長度為2的冪的優點:

  • 1.hash效率高。 put階段,要判斷該node放到陣列的哪個桶裡,採用的方式是table[(n-1)&hash(key)],n是2的冪,n-1的二進位制位上全部是1,這樣和hash值位與運算,可以更高效率的求出該hash值對應的陣列下標。
  • 2.resize效率高。(具體程式碼實現在hashmap.resize()中,)resize階段,擴容2倍,陣列大小n的二進位制位數增加1,在rehash的時候,hash值得最高位是0,那麼該node不需要移動。只要在hash值最高位是1的時候,rehash的值才會發生變化,而且是增加2的n-1次方。這樣擴容的效率更高。
    /**
     * Computes key.hashCode() and spreads (XORs) higher bits of hash
     * to lower.  Because the table uses power-of-two masking, sets of
     * hashes that vary only in bits above the current mask will
     * always collide. (Among known examples are sets of Float keys
     * holding consecutive whole numbers in small tables.)  So we
     * apply a transform that spreads the impact of higher bits
     * downward. There is a tradeoff between speed, utility, and
     * quality of bit-spreading. Because many common sets of hashes
     * are already reasonably distributed (so don't benefit from
     * spreading), and because we use trees to handle large sets of
     * collisions in bins, we just XOR some shifted bits in the
     * cheapest possible way to reduce systematic lossage, as well as
     * to incorporate impact of the highest bits that would otherwise
     * never be used in index calculations because of table bounds.
     */
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
複製程式碼

hash(Object key)方法是對key求hash雜湊值,比直接用hashcode更好,因為h無符號右移16位後得到高位,

V Get(Object key)方法

通過getNode(hash(key), key)獲得。程式碼邏輯:

        final Node<K,V> getNode(int hash, Object key) {
        //陣列tab,首節點first,陣列大小n,
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        //三個條件判斷,&&具有短路功能,注意先後順序。
        //1.陣列非空,2.陣列長度大於零,3,node節點非空.or 直接return null;
        if ((tab = table) != null && (n = tab.length) > 0 && (first = tab[(n - 1) & hash]) != null) {
            //判斷是否是first:hash值是否相同&&  key引用相同或者equals.(k)
            if (first.hash == hash && ((k = first.key) == key || (key != null && key.equals(k))))
                return first;
            if ((e = first.next) != null) {
                //判斷是紅黑樹or連結串列
                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;
    }
複製程式碼

map的key可以是null

以上get程式碼可以發現,如果key是null,hash(null)=0,固定在陣列的0下標處。null==null位true。

put(key,value)

使用如下方法:

/**
     * 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;
        //如果陣列為空,則通過resize()初始化陣列。
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        // 陣列裡面,還沒有node物件則新建;否則新建Node物件插入該Node。
        //插入桶,分為兩種情況,一種是紅黑樹。一種是連結串列。
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                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;
                }
            }
            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;
    }
複製程式碼

以上程式碼用的重要方法為resize,treeifyBin。以下為原始碼:

     /**
     * 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;
    }
複製程式碼

還有個treeifyBin方法,把該桶裡面的單項鍊錶轉換為雙向連結串列,然後再轉換為紅黑樹。關於紅黑樹的具體實現,這邊文章先不分析。

remove方法

用到的final Node<K,V> removeNode方法是final,不能被子類重寫,只能重新afterNodeRemoval方法來增加邏輯。 removeNode原始碼主要考慮了單節點, 連結串列和樹三種情況,主要邏輯是(每一步都要考慮三種情況):

  • 1,先找到key這個節點,
  • 2,然後再刪除這個節點。

keys() values(),entrySet()都提供了一個該hashmap的視窗。

computeIfAbsent

java8之前。從map中根據key獲取value操作可能會有下面的操作
Object key = map.get("key"); if (key == null) { key = new Object(); map.put("key", key); }

java8之後。上面的操作可以簡化為一行,若key對應的value為空,會將第二個引數的返回值存入並返回

Object key2 = map.computeIfAbsent("key", k -> new Object());
複製程式碼

相關文章