HashMap JDK9源码解读

来源:互联网 发布:python开发过哪些软件? 编辑:程序博客网 时间:2024/06/04 18:06

1、属性值

  static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16默认的表长度

static final int MAXIMUM_CAPACITY = 1 << 30;//最大的

 static final float DEFAULT_LOAD_FACTOR = 0.75f;

    /**
     * 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;//列表长度超过8进行转换为树结构


    /**
     * The bin count threshold for untreeifying a (split) bin during a
     * resize operation. Should be less than TREEIFY_THRESHOLD, and at
     * most 6 to mesh with shrinkage detection under removal.
     */
    static final int UNTREEIFY_THRESHOLD = 6;//当bin的个数小于6时由树形调整为列表


    /**
     * The smallest table capacity for which bins may be treeified.
     * (Otherwise the table is resized if too many nodes in a bin.)
     * Should be at least 4 * TREEIFY_THRESHOLD to avoid conflicts
     * between resizing and treeification thresholds.
     */
    static final int MIN_TREEIFY_CAPACITY = 64;//当总bin的个数大于64时,且单列bin的个数大于8时才能由列表调整为树。

    transient Node<K,V>[] table;//为记录的数组

2、构造实现方式:构造只是赋值属性初始值但是不会真正初始化数组表空间,在第一次添加元素时形成数组表空间。这个和以往的jDK1.7之前的不同,1.7之前的都是在构造里初始化了table数组空间。

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

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

3、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;
        if ((tab = table) == null || (n = tab.length) == 0)//判断数组表是否为空,如果为空进行表空间扩容初始化。在第一次添加元素时用到
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)//和数组table的长度-1进行相与得出在数组中的位置,看位置是否为空,如果为空说明这个位置还没有元素占用,new一个Node内部类节点赋值给数组。
            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))))//判断原数组存储的是否同一个key元素,如果是通过变量e记录下该位置,以便在下面把该元素的value替换为新值
                e = p;
            else if (p instanceof TreeNode)//判断是否为树形结构如果是,通过树形结构查找或者添加
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);////如果是树形结构找到原key的节点,如果没有找到进行添加新元素到树形结构
            else {//遍历链表
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {//如果找到链表尾部也没有找到相同key的元素,说明该链表没有原值进行新new一个node添加到链表
                        p.next = newNode(hash, key, value, null);
                        if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st//如果遍历的链表长度大于=8转换为树形结构
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))//如果遍历过程中找到形同key的元素,e记录位置后跳出循环
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key//如果e不为空说明找到原来的key,把原理node的值赋予新值
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)//添加一个元素后size进行加1,如果目前存在元素大于最大容量后进行扩容,
            resize();
        afterNodeInsertion(evict);
        return null;
    }

4、容器扩容

 final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        int oldCap = (oldTab == null) ? 0 : oldTab.length;//如果第一次添加元素table为null,此值为0,否则为老表的长度
        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)//如果原来有容量,进行把原容量扩大2倍,把table长度扩大2倍
                newThr = oldThr << 1; // double threshold//实际的存储值容量也扩大为2倍
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults //第一次添加默认初始化的容量值16 
            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
        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)//该数组位置存储的为单个node对象没有链表,直接把该node的hash值和新的table-1进行相与取得新的存储位置
                        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) {//这里是一个非常精妙的设计和原来的JDK1.7以前的版本差距很大,原来的都是为再hash(e.hash & (table.length - 1))判断位置,现在为(e.hash & oldCap)判断mask范围在高位多1bit是否有值,如果有值新在位置为(原索引+oldCap)否则为原索引位置,具体描述图示参加下面:链表扩容后的序列计算
                                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;
    }

5、链表扩容后的序列计算

经过观测可以发现,我们使用的是2次幂的扩展(指长度扩为原来2倍),所以,元素的位置要么是在原位置,要么是在原位置再移动2次幂的位置。看下图可以明白这句话的意思,n为table的长度,图(a)表示扩容前的key1和key2两种key确定索引位置的示例,图(b)表示扩容后key1和key2两种key确定索引位置的示例,其中hash1是key1对应的哈希与高位运算结果。

hashMap 1.8 哈希算法例图1

元素在重新计算hash之后,因为n变为2倍,那么n-1的mask范围在高位多1bit(红色),因此新的index就会发生这样的变化:

hashMap 1.8 哈希算法例图2

因此,我们在扩充HashMap的时候,不需要像JDK1.7的实现那样重新计算hash,只需要看看原来的hash值新增的那个bit是1还是0就好了,是0的话索引没变,是1的话索引变成“原索引+oldCap”,可以看看下图为16扩充为32的resize示意图:

jdk1.8 hashMap扩容例图

这个设计确实非常的巧妙,既省去了重新计算hash值的时间,而且同时,由于新增的1bit是0还是1可以认为是随机的,因此resize的过程,均匀的把之前的冲突的节点分散到新的bucket了。

6、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;
        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))))//table的第一个值正好是取的值
                return first;
            if ((e = first.next) != null) {
                if (first instanceof TreeNode)//如果是树形结构通过树形方法遍历取node
                    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;
    }

7、remove删除node

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


    /**
     * Implements Map.remove and related methods
     *
     * @param hash hash for key
     * @param key the key
     * @param value the value to match if matchValue, else ignored
     * @param matchValue if true only remove if value is equal
     * @param movable if false do not move other nodes while removing
     * @return the node, or null if none
     */
    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)))) //如果table数组为该值记录位置
                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)))) {//找到要的node位置,根据node的结构处理
                if (node instanceof TreeNode)//如果为树形
                    ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
                else if (node == p)//如果table数组为该node值记录位置
                    tab[index] = node.next;
                else//如为链表
                    p.next = node.next;
                ++modCount;
                --size;
                afterNodeRemoval(node);
                return node;
            }
        }
        return null;
    }

图片参考:http://www.importnew.com/20386.html