java 1.8 hashmap 源码分析

1.摘要

    java 1.8优化了HashMap代码,主要有hash值计算方法,添加红黑树,resize顺序保证等,下面将一一进行阐述。

2.HashMap简介

    HashMap和HashTable的区别在于hashtable是线程安全的,而且不允许有null值,而HashMap允许一个键为null,多个值为null。但是HashTable为遗留类,如果需要线程安全,可以使用性能更高的ConcurrentHashMap(使用了分段锁)。

    HashMap还有LinkedHashMap和TreeHashMap两个子类,LinkedHashMap保存数据插入顺序,TreeHashMap会对插入的key进行排序。

    HashMap是一个Node数组(哈希桶数组),每个数组的元素是一个链表或者红黑树,默认如果链表的长度超过8会自动转换为红黑树。

3.计算hash值

    本质上为三个计算: 求hash值,高位运算,取模运算。

    代码为:

//求hash值、高位运算
(h=key.hashCode()) ^ (h >>> 16)
//取模
i = h & (length-1)

《java 1.8 hashmap 源码分析》

4. put方法

思路:哈希桶数组是否为空;通过key.hashCode得到数组下标,判断该哈希桶是否为空;判断该key值在哈希桶中是否存在。

1)判断哈希桶数组是否为空,若是,新建Node,直接跳到8;

2)获取下标,判断该哈希桶是否为空,若是,新建Node,直接跳到8;

3)新建缓存变量Node<K, V> e ;

4)判断该桶的key是否相等,将该Node赋值给e;

5)判断该桶是否为红黑树,如果是,插入e;

6)for循环遍历链表

6.1)没有相同的key,末端添加new Node;

6.2)有相同的key,break;

7)如果e非空,保存e中的旧值,赋值新值,并返回旧值;

8)size增加,并判断是否需要resize。

源码如下:

    /**
     * Associates the specified value with the specified key in this map.
     * If the map previously contained a mapping for the key, the old
     * value is replaced.
     *
     * @param key key with which the specified value is to be associated
     * @param value value to be associated with the specified key
     * @return the previous value associated with <tt>key</tt>, or
     *         <tt>null</tt> if there was no mapping for <tt>key</tt>.
     *         (A <tt>null</tt> return can also indicate that the map
     *         previously associated <tt>null</tt> with <tt>key</tt>.)
     */
    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;
        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;
    }

5. resize方法

思路:计算newCap,newThr;新建容量为newCap的Node数组;将之前数组的值拷贝到新数组。

要强调的是

    1. java 1.7拷贝数组的方法是挨个计算key的hash值对应的下标i,并将相应的Node放到tab[i]的头,这样会导致存放顺序相反。java 1.8中,因为扩容后newCap为oldCap的两倍,在hash值取模后,可能不一样的地方只在newCap的最高位,所以旧数组下标i的元素只可能被分配到i或者i+oldCap的下标中,故,只要新建两个链表,将对应不同下标的值赋给不同的链表,然后将两个链表在赋值给table[i]和table[i+oldCap],就保证了Node的顺序一致性;

    2. 在resize往新的链表中插入Node的时候,如果链表的长度大于8,会将链表转为红黑树。

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

参考

Java 8系列之重新认识HashMap

    原文作者:yangguanghaozi
    原文地址: https://blog.csdn.net/yangguanghaozi/article/details/72357987
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞