java hashmap(jdk1.8)源码分析

以下是个人浅薄分析,如有不对请赐教。

重点方法加粗

首先看看几个常量。

  static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
    static final int MAXIMUM_CAPACITY = 1 << 30;
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
    static final int TREEIFY_THRESHOLD = 8;
    static final int UNTREEIFY_THRESHOLD = 6;
    static final int MIN_TREEIFY_CAPACITY = 64;

可以看出,默认初始容量为16,最大为2^30,也即Integer.MAX_VALUE的一半左右,默认负载因子0.75,链表长度超过8后转为红黑树,退到6后又转回链表(给点空间,避免频繁转换),大家知道红黑树是很高效的,链表长了查找会变慢,转为红黑树还有个条件就是表(数组)的容量达到阈值64,如果链表长度达到8而容量未到64,就先扩容数组。

下面是fields,很简单,不解释,需要注意下modCount。

    transient Node<K,V>[] table;

    transient Set<Map.Entry<K,V>> entrySet;

    transient int size;

    transient int modCount;

    int threshold;

    final float loadFactor;
 

构造器有4个,一个无参,一个参数为初始容量,一个参数为map,另一个在下面,可以看到最后调用了方法tableSizeFor对初始容量进行修整。

    public HashMap(int initialCapacity, float loadFactor) {
        if (initialCapacity < 0)
            throw new IllegalArgumentException("Illegal initial capacity: " +
                                               initialCapacity);
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;
        if (loadFactor <= 0 || Float.isNaN(loadFactor))
            throw new IllegalArgumentException("Illegal load factor: " +
                                               loadFactor);
        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

------------------------------------------------------------------------------------------------------------------------------

key的hash值算法

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

以上是key的hash值计算方法,相较于jdk1.7的四次扰动,这里只使用了一次,key的hashcode为int32位,与自身(无符号)右移16位做与运算,是为了将hashcode的低位更加随机,且位数变少。转载个图过来展示一下,可以看到,取低9位计算index(计算代码在下面),也即哈希表长度为512的时候,碰撞次数减少约10%,只用一次扰动应该是觉得多次扰动效果并不明显吧。


index的计算如下,这里n是哈希表容量(数组大小),hash为key的hash(),这个运算等价于于对n取模,不信你用16的容量跟各种hash值按位与试试看。这个位运算是很快的,为什么容量为2的幂次方就体现在这里,如果n不是2的幂次方,那么这个位运算和取模运算就无法保证结果一致了。

(n - 1) & hash

下面再看看跟哈希表容量设置有关的一个方法tableSizeFor

    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的幂次方,那么它会帮你找到一个2的幂次方的值,刚好大于你给的初始值。具体过程很简单,就是将你给的值的二进制数的第一个高位1不断右移并做或运算,使这个1后面都变成1,然后再加上1,就得到一个2的幂次方的值了。比如13为1101,先变成1111,加1,变成16。

----------------------------------------------------------------------------------

下面是一个内部类,是链表的节点类,哈希表数组的每个位置都准备存储一个开始的节点。还有一个为红黑树服务的TreeNode节点类,差不多就不上代码了。

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

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

--------------------------------------------------------------------------------------------------------------

下面看一下get方法,它是通过getNode实现的

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

getNode里面,先判断表是不是null的,表的长度是不是0,以及要从表找的那个位置(hash&(n-1) 前面说过)中,元素是不是null的。

然后判断hash及key是不是跟链表的头节点一致,一致就返回,不然继续找。

继续找的时候先看看这个链表是否转成了红黑树,如果转了,就用红黑树的方法去找,速度要快。

如果没有,就一直next的找下去。找不到返回null。

    final Node<K,V> getNode(int hash, Object key) {
        Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
        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;
    }

getTreeNode这个方法依赖root和find方法,具体是先找到根节点然后调用find方法。parent如果为null表示现在的节点即是root。

        final TreeNode<K,V> getTreeNode(int h, Object k) {
            return ((parent != null) ? root() : this).find(h, k, null);
        }

root方法很简单,不断追本溯源,找到root。

        final TreeNode<K,V> root() {
            for (TreeNode<K,V> r = this, p;;) {
                if ((p = r.parent) == null)
                    return r;
                r = p;
            }
        }
find方法根据hash值大小从root往下找,如果自定义了按某个类的compareTo方法进行比较,就以该方法判断往左还是右查找。

        final TreeNode<K,V> find(int h, Object k, Class<?> kc) {
            TreeNode<K,V> p = this;
            do {
                int ph, dir; K pk;
                TreeNode<K,V> pl = p.left, pr = p.right, q;
                if ((ph = p.hash) > h)
                    p = pl;
                else if (ph < h)
                    p = pr;
                else if ((pk = p.key) == k || (k != null && k.equals(pk)))
                    return p;
                else if (pl == null)
                    p = pr;
                else if (pr == null)
                    p = pl;
                else if ((kc != null ||
                          (kc = comparableClassFor(k)) != null) &&
                         (dir = compareComparables(kc, k, pk)) != 0)
                    p = (dir < 0) ? pl : pr;
                else if ((q = pr.find(h, k, kc)) != null)
                    return q;
                else
                    p = pl;
            } while (p != null);
            return null;
        }
--------------------------------------------------------------------------------------------------------------------------------

然后是put方法,依赖putVal方法

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

putVal方法里,先判断表是否null或表容量是否为0,如果是就先扩容。

然后判断要放进表中的位置是否没有节点存在,如果是,就直接把这个节点作为头节点放进去。modCount+1,size+1,判断是否需要扩容,然后返回前一个也就是null。

否则,先判断这个头节点位置的key是不是跟要插入节点的key相同,如果是,先放进节点e中。然后更新e中的值(其实这里新的值和旧的值相等,但这是一个公有代码片段),返回旧值。

如果头节点key跟插入的key不一样,且头节点是红黑树的节点,就调用红黑树的方法。

否则还是以链表的方式进行,不断的next下去:

1;如果到了链表末尾,就将新节点插入到后面即可。然后看看插入后是否达到链表转红黑树的条件,达到就转成红黑树。

2;如果找到某个节点key和要插入的相同,退出循环,也是更新e中的值。同样在代码的最后,检查是否需要扩容(更新又不是插入新节点,当然不用啦)

如果表达到阈值,也要扩容。afterNodeInsertion和afterNodeAccess这2个方法是回调用的,hashmap里为空。

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

下面看看已经是红黑树时,红黑树的put方法:

先找到根节点,如果根节点的key等于要插入节点的key,返回进行更新即可。如果自定义比较器,根据自定义的寻找插入点。

否则一直找到末尾为止,将新节点插入左或右节点,插入后进行调整,保证树依然是红黑树。

xpn!=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)))
                    return p;
                else if ((kc == null &&
                          (kc = comparableClassFor(k)) == null) ||
                         (dir = compareComparables(kc, k, pk)) == 0) {
                    if (!searched) {
                        TreeNode<K,V> q, ch;
                        searched = true;
                        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;
                }
            }
        }

再看看从链表转为红黑树的方法:

先看看是否需要对表扩容

然后看看头节点非空(你要转红黑树当然有节点了)

然后将这个单向链表转成双向

    final void treeifyBin(Node<K,V>[] tab, int hash) {
        int n, index; Node<K,V> e;
        if (tab == null || (n = tab.length) < MIN_TREEIFY_CAPACITY)
            resize();
        else if ((e = tab[index = (n - 1) & hash]) != null) {
            TreeNode<K,V> hd = null, tl = null;
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null);
                if (tl == null)
                    hd = p;
                else {
                    p.prev = tl;
                    tl.next = p;
                }
                tl = p;
            } while ((e = e.next) != null);
            if ((tab[index] = hd) != null)
                hd.treeify(tab);
        }
    }

再看看treeify方法:

这个方法是将双向链表转为红黑树,具体的跟数据结构有关,红黑树也不算复杂。

final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null;
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next;
                x.left = x.right = null;
                if (root == null) {
                    x.parent = null;
                    x.red = false;
                    root = x;
                }
                else {
                    K k = x.key;
                    int h = x.hash;
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root;;) {
                        int dir, ph;
                        K pk = p.key;
                        if ((ph = p.hash) > h)
                            dir = -1;
                        else if (ph < h)
                            dir = 1;
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p;
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x;
                            else
                                xp.right = x;
                            root = balanceInsertion(root, x);
                            break;
                        }
                    }
                }
            }
            moveRootToFront(tab, root);
        }

再看看比较重要的resize方法:

1;如果旧表容量大于0:

1.1;如果它大于等于最大允许容量(不可能大于,因为旧表也是扩容而来的),旧的阈值为Integer的最大值,容量没法增加了,直接返回旧表。

1.2;如果旧表容量小于最大允许值的一半,并且旧表容量大于默认值,新表容量为旧表*2,阈值也为旧表*2

2;如果旧表容量小于等于0(空表),并且旧表阈值大于0,新表容量设为旧表阈值

3;如果旧表容量小于等于0,并且旧表阈值小于等于0,新表容量和阈值为默认值

以上进行完后,再进行一些判断:

如果新表阈值为0(对应上面2),如果新表容量小于最大允许值并且新表容量*负载因子小于最大允许值,则新表阈值为新表容量*负载因子,否则为Integer的最大值。

至此新表的容量和阈值都设置好了。

然后将旧表的数据倒腾到新表中,并删除旧表中元素。

这里值得提出的是,倒腾数据时,是将新表分成2个部分,每个部分大小等于旧表。请看if ((e.hash & oldCap) == 0)这个判断条件,之前根据key的hash值寻找数组位置是用hash&(n-1),而这里是hash&oldCap,仔细分析就可知道,当其等于0时,表明这个节点应该在新表的第一部分进行插入,不等于0时在第二部分进行插入,在这里,应该又体现出容量为2的幂次方的作用

对于旧表中数组index为i的e节点,它在新表中就可能分布在第一和第二部分了,loHead和loTail表示它在第一部分的链表的头节点和尾节点,hiHead和hiTail表示它在第二部分的链表的头节点和尾节点。当然,是先用2个链表存储旧表中的一个链表,然后将2个链表放入对应新表的位置中(索引应该是i和i+oldCap)。


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

将红黑树拆分节点。

        final void split(HashMap<K,V> map, Node<K,V>[] tab, int index, int bit) {
            TreeNode<K,V> b = this;
            // Relink into lo and hi lists, preserving order
            TreeNode<K,V> loHead = null, loTail = null;
            TreeNode<K,V> hiHead = null, hiTail = null;
            int lc = 0, hc = 0;
            for (TreeNode<K,V> e = b, next; e != null; e = next) {
                next = (TreeNode<K,V>)e.next;
                e.next = null;
                if ((e.hash & bit) == 0) {
                    if ((e.prev = loTail) == null)
                        loHead = e;
                    else
                        loTail.next = e;
                    loTail = e;
                    ++lc;
                }
                else {
                    if ((e.prev = hiTail) == null)
                        hiHead = e;
                    else
                        hiTail.next = e;
                    hiTail = e;
                    ++hc;
                }
            }

            if (loHead != null) {
                if (lc <= UNTREEIFY_THRESHOLD)
                    tab[index] = loHead.untreeify(map);
                else {
                    tab[index] = loHead;
                    if (hiHead != null) // (else is already treeified)
                        loHead.treeify(tab);
                }
            }
            if (hiHead != null) {
                if (hc <= UNTREEIFY_THRESHOLD)
                    tab[index + bit] = hiHead.untreeify(map);
                else {
                    tab[index + bit] = hiHead;
                    if (loHead != null)
                        hiHead.treeify(tab);
                }
            }
        }


再看看remove方法:

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

removeNode方法:

先判断对应数组位置头节点是否存在

如果头节点即是要异常的node,则直接移除,将下一个设为头节点

否则,如果是红黑树,用红黑树的查找方法,不是就循环查找

删除也一样,如果是红黑树,用红黑树的删除方法(这里要判断是否由红黑树转回链表)

具体细节熟悉红黑树就很好理解了。

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

-------------------------------------------------------------------------------------------------------------------------------

下面方法判断一个类A是否实现了Comparable<A>,如果是,返回其Class类型。

先判断是否实现了Comparable,然后先检查是否是String类型(估计因为这个可能性大,单独拿出来判断了)

然后获得对象x的所有实现接口,判断接口是否是参数化的,并且接口是Comparable,并且参数只有一个且为A

   static Class<?> comparableClassFor(Object x) {
        if (x instanceof Comparable) {
            Class<?> c; Type[] ts, as; Type t; ParameterizedType p;
            if ((c = x.getClass()) == String.class) // bypass checks
                return c;
            if ((ts = c.getGenericInterfaces()) != null) {
                for (int i = 0; i < ts.length; ++i) {
                    if (((t = ts[i]) instanceof ParameterizedType) &&
                        ((p = (ParameterizedType)t).getRawType() ==
                         Comparable.class) &&
                        (as = p.getActualTypeArguments()) != null &&
                        as.length == 1 && as[0] == c) // type arg is c
                        return c;
                }
            }
        }
        return null;
    }
如果x的类型为kc,就比较x和k。

    @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable
    static int compareComparables(Class<?> kc, Object k, Object x) {
        return (x == null || x.getClass() != kc ? 0 :
                ((Comparable)k).compareTo(x));
    }

以上是2个辅助方法。

综上,重要的在hash值的计算,put/get方法,resize方法。当然源码还有很多类是方法,就不提了。







  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值