JDK8 HashMap的实现之4(共四篇)

1. put的实现

 

public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //如果当前map中无数据,执行resize方法。并且返回n  
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //如果要插入的键值对要存放的这个位置刚好没有元素,那么把他封装成Node对象,放在这个位置上就完事了  
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
       //否则的话,说明这上面有元素  
        else {
            Node<K,V> e; K k;
            //如果这个元素的key与要插入的一样,那么就替换一下,也完事。
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            //1.如果当前节点是TreeNode类型的数据,执行putTreeVal方法  
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
            	//还是遍历这条链子上的数据,跟jdk6没什么区别 
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                        p.next = newNode(hash, key, value, null);
                        //2.完成了操作后多做了一件事情,判断,并且可能执行treeifyBin方法
                        //长度是否达到阈值,需要把链表换成树的形式
                        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;
    }

 final TreeNode<K,V> putTreeVal(HashMap<K,V> map, Node<K,V>[] tab,
                                       int h, K k, V v) {
            Class<?> kc = null;
            boolean searched = false;
            // 查找到根节点
            TreeNode<K,V> root = (parent != null) ? root() : this;
            for (TreeNode<K,V> p = root;;) {
                int dir, ph; K pk;
                if ((ph = p.hash) > h)
                    dir = -1;
                else if (ph < h)
                    dir = 1;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                	// 如果发现红黑树某个节点的key和要put的相同,返回就可以了
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                	// hash相等,且key无法比较或者相等
                    if (!searched) {// 如果查找过没有相同的节点,下次就不用再找了
                        TreeNode<K,V> q, ch;
                        searched = true;
                        // 双空节点或者左子树右子树都没有和这个key一样的节点的时候就不会return q了。
                        if (((ch = p.left) != null &&
                             (q = ch.find(h, k, kc)) != null) ||
                            ((ch = p.right) != null &&
                             (q = ch.find(h, k, kc)) != null))
                            return q;
                    }
                    //哈希值相等,但键无法比较,只好通过特殊的方法给个结果
                    dir = tieBreakOrder(k, pk);
                }

                TreeNode<K,V> xp = p;
                if ((p = (dir <= 0) ? p.left : p.right) == null) {
                    Node<K,V> xpn = xp.next;
                    TreeNode<K,V> x = map.newTreeNode(h, k, v, xpn);
                    if (dir <= 0)
                        xp.left = x;
                    else
                        xp.right = x;
                    xp.next = x;
                    x.parent = x.prev = xp;
                    if (xpn != null)
                        ((TreeNode<K,V>)xpn).prev = x;
                    // 进过调整之后,根节点可能不是第一个节点了,调整一下。
                    moveRootToFront(tab, balanceInsertion(root, x));
                    return null;
                }
            }
        }

 static <K,V> TreeNode<K,V> balanceInsertion(TreeNode<K,V> root,
                                                    TreeNode<K,V> x) {
        	//插入的节点必须是红色的,除非是根节点
            x.red = true;
            //遍历到x节点为黑色,整个过程是一个上滤的过程
            for (TreeNode<K,V> xp, xpp, xppl, xppr;;) {
            	// case 0.插入节点z为根节点——这种情况好办,直接染黑完事,我们不讨论
                if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
                //如果xp的黑色就直接完成,最简单的情况
                //case 1.父节点为黑色节点——这种情况最好办,根本没有破坏红黑树的五大性质,不需要做任何调整,我们不讨论
                else if (!xp.red || (xpp = xp.parent) == null)
                    return root;
              //如果x的父节点是x父节点的左节点
                if (xp == (xppl = xpp.left)) {
                	//x的父亲节点的兄弟是红色的(需要颜色翻转)
                	// case 2.父节点为红色节点,叔节点也为红色
                    if ((xppr = xpp.right) != null && xppr.red) {
                    	//x父亲节点的兄弟节点置成黑色
                        xppr.red = false;
                        //父节点一样是黑色
                        xp.red = false;
                        //祖父节点置成红色
                        xpp.red = true;
                        //然后上滤(就是不断的重复上面的操作)
                        x = xpp;
                    }
                    else {
                    	//如果x是xp的右节点整个要进行两次旋转,先左旋转再右旋转
                    	//case 3.父节点为红色节点,叔节点为黑色节点,当前节点为右孩子
                        if (x == xp.right) {
                            root = rotateLeft(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        // case 4.父节点为红色节点,叔节点为黑色节点,当前节点为左孩子
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateRight(root, xpp);
                            }
                        }
                    }
                }
                //以左节点镜像对称就不做具体分析了 
                else {
                    if (xppl != null && xppl.red) {
                        xppl.red = false;
                        xp.red = false;
                        xpp.red = true;
                        x = xpp;
                    }
                    else {
                        if (x == xp.left) {
                            root = rotateRight(root, x = xp);
                            xpp = (xp = x.parent) == null ? null : xp.parent;
                        }
                        if (xp != null) {
                            xp.red = false;
                            if (xpp != null) {
                                xpp.red = true;
                                root = rotateLeft(root, xpp);
                            }
                        }
                    }
                }
            }
        }


2.remove的实现

 

 

public V remove(Object key) {
        Node<K,V> e;
        return (e = removeNode(hash(key), key, null, false, true)) == null ?
            null : e.value;
    }

 final Node<K,V> removeNode(int hash, Object key, Object value,
                               boolean matchValue, boolean movable) {
        Node<K,V>[] tab; Node<K,V> p; int n, index;
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (p = tab[index = (n - 1) & hash]) != null) {
            Node<K,V> node = null, e; K k; V v;
            // 先找出要删除的节点node
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                node = p;
            else if ((e = p.next) != null) {
                if (p instanceof TreeNode)
                    node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
                else {
                    do {
                        if (e.hash == hash &&
                            ((k = e.key) == key ||
                             (key != null && key.equals(k)))) {
                            node = e;
                            break;
                        }
                        p = e;
                    } while ((e = e.next) != null);
                }
            }
            if (node != null && (!matchValue || (v = node.value) == value ||
                                 (value != null && value.equals(v)))) {
                if (node instanceof TreeNode)
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                // 如果是首节点
                else if (node == p)
                    tab[index] = node.next;
                else// 非首节点
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

static <K,V> TreeNode<K,V> balanceDeletion(TreeNode<K,V> root,
                                                   TreeNode<K,V> x) {
            for (TreeNode<K,V> xp, xpl, xpr;;)  {
                if (x == null || x == root)
                    return root;
                else if ((xp = x.parent) == null) {
                    x.red = false;
                    return x;
                }
                //case 1 x是红色的,是最容易解决的,直接染黑就是了。
                else if (x.red) {
                    x.red = false;
                    return root;
                }
                else if ((xpl = xp.left) == x) {
                	// case 2 x的兄弟节点是红色的,染黑兄弟节点,染红父节点,左旋转父节点,重置兄弟节点
                    if ((xpr = xp.right) != null && xpr.red) {
                        xpr.red = false;
                        xp.red = true;
                        root = rotateLeft(root, xp);
                        xpr = (xp = x.parent) == null ? null : xp.right;
                    }
                    if (xpr == null)
                        x = xp;
                    else {
                    	// case 3 x的兄弟节点w是黑色的,而且w的两个子节点都是黑色的
                        TreeNode<K,V> sl = xpr.left, sr = xpr.right;
                        if ((sr == null || !sr.red) &&
                            (sl == null || !sl.red)) {
                            xpr.red = true;
                            x = xp;
                        }
                        else {
                        	//  case 4 x的兄弟节点w是黑色的,w的左儿子是红色的,w的右孩子是黑色的
                            if (sr == null || !sr.red) {
                                if (sl != null)
                                    sl.red = false;
                                xpr.red = true;
                                root = rotateRight(root, xpr);
                                xpr = (xp = x.parent) == null ?
                                    null : xp.right;
                            }
                            // case 5  x的兄弟节点w是黑色的,且w的右孩子是红色的。
                            if (xpr != null) {
                                xpr.red = (xp == null) ? false : xp.red;
                                if ((sr = xpr.right) != null)
                                    sr.red = false;
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateLeft(root, xp);
                            }
                            x = root;
                        }
                    }
                }
                // x是右节点情况,和左节点操作是对称的,不讨论 
                else { // symmetric
                    if (xpl != null && xpl.red) {
                        xpl.red = false;
                        xp.red = true;
                        root = rotateRight(root, xp);
                        xpl = (xp = x.parent) == null ? null : xp.left;
                    }
                    if (xpl == null)
                        x = xp;
                    else {
                        TreeNode<K,V> sl = xpl.left, sr = xpl.right;
                        if ((sl == null || !sl.red) &&
                            (sr == null || !sr.red)) {
                            xpl.red = true;
                            x = xp;
                        }
                        else {
                            if (sl == null || !sl.red) {
                                if (sr != null)
                                    sr.red = false;
                                xpl.red = true;
                                root = rotateLeft(root, xpl);
                                xpl = (xp = x.parent) == null ?
                                    null : xp.left;
                            }
                            if (xpl != null) {
                                xpl.red = (xp == null) ? false : xp.red;
                                if ((sl = xpl.left) != null)
                                    sl.red = false;
                            }
                            if (xp != null) {
                                xp.red = false;
                                root = rotateRight(root, xp);
                            }
                            x = root;
                        }
                    }
                }
            }
        }

 

 

 

 

 

3.resize实现

 

  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) {
        	// table长度太大了,阈值就不管了,不再扩容。
            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;
                    // 如果该位置只有一个节点,直接移过去心的tab就好了
                    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;
    }

这里的高低串说明一下,hashMap求某个hash值落在table哪个index的算法是hash & (cap - 1) ,因为cap是2的倍数,也就是求hash有多少个1了。当发生扩总newCap是cap的两倍。这时候rehash重定位会发生两种情况:

1.情况1是hash1 & oldCap == 0,这里假设某个key的hash值为hash1,再次计算hash1的index时候公式为hash1 & (newCap -1)。因为(newCap -1)的最高位和oldCap的最高位是一样的,都是1,这里为方便说明假设最高位为第n位。hash1 & oldCap == 0说明hash1的第n位为0,而(newCap -1)高于第n为的也为0,则hash1 & (newCap -1) == hash1 & (oldCap - 1)。总的来说,其实hash1 & oldCap == 0就说明了hash1和newCap 的第二高位对应的那位是0,意思是扩容后,这类型的hash所对应的index不变。

举个例子,比如当oldCap = 10,newCap = 100,hash1 = 01 时。发生扩容前hash1的index为hash & (oldCap - 1)= 01 & 01 = 1;发生扩容后hash1的index为hash & (newCap - 1)= 01 & 011 = 1;

 

2.情况2是hash2 & oldCap !=0,这里假设某个key的hash值为hash2,就说明了hash2和newCap 的第二高位对应的那位是1,那么hash2 & (newCap -1)  == hash2 & (oldCap -1)  + oldCap ==  hash2 & oldIndex  + oldCap。

举个例子,比如当oldCap = 10,newCap = 100,hash2 = 11 时。发生扩容前hash2的index为 

hash2 & (10 - 1)   ==  1;发生扩容后hash2的index为hash2 & (100 - 1) = hash2 & (10 - 1)  + 10 == 1 + 10 = 11

 

 

 

 

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