JDK1.8 HashMap源码学习

HashMap数据结构:
1.8数据结构

图片来源:【集合框架】JDK1.8源码分析之HashMap(一)

1.8 引用红黑树数据结构,提高了查询效率

构造函数和相关参数:

这里和1.7差不多,由于引入了红黑树的数据结构,多了 TREEIFY_THRESHOLD、UNTREEIFY_THRESHOLD、MIN_TREEIFY_CAPACITY 这几个参数

    /**
     * 默认初始化容量大小 16 , 必须是2的幂次方
     */
    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;

    /**
     * 转化为红黑树阈值
     */
    static final int TREEIFY_THRESHOLD = 8;

    /**
     * 红黑树中的元素个数小于6就会还原为链表
     */
    static final int UNTREEIFY_THRESHOLD = 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;


    /**
     * 设置初始化容量和负载因子的构造函数
     */
    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);
    }

    /**
     * 设置初始化容量的构造函数
     * 默认负载因子是0.75
     */
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

    /**
     * 默认构造函数
     * 默认长度是16,默认负载因子是0.75
     */
    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

    /**
     * 
     */
    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        putMapEntries(m, false);
    }

put()方法
58e67eae921e4b431782c07444af824e_r.jpg

图片来源:Java 8系列之重新认识HashMap

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    // 计算哈希值
    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }
    
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 如果table为空则进行初始化,扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            // 1.7是调用inflateTable()方法进行初始化,1.8则是调用resize()
            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) {
                        // 放置新元素时,放到尾部,使用尾插法,JDK1.7使用头插法
                        // 使用这个方法也可以避免在多线程扩容时造成循环链表
                        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;
    }

扩容:

    final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table;
        // 当前容量
        int oldCap = (oldTab == null) ? 0 : oldTab.length;
        // 当前扩容的阈值
        int oldThr = threshold;
        int newCap, newThr = 0;
        // 如果当前容量大于0
        if (oldCap > 0) {
            // 如果当前容量大小等于之前设置的允许最大值
            if (oldCap >= MAXIMUM_CAPACITY) {
                // 将扩容的阈值设置为int类型的最大值,并返回原来的数组
                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
            // 如果容量为0,且扩容阈值大于0,设置新容量为当前扩容的阈值
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults
            // 数组为空时则创建默认容量大小的,第一次put会调用到
            newCap = DEFAULT_INITIAL_CAPACITY;
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
        }
        // 如果新的扩容阈值为0,重新计算阈值
        if (newThr == 0) {
            float ft = (float)newCap * loadFactor;
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                      (int)ft : Integer.MAX_VALUE);
        }
        将新阈值赋值给threshold
        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;
                            // 如果e的hash和旧容量相与为0
                            if ((e.hash & oldCap) == 0) {
                                // 如果loTail为空,表示该节点为第一个节点
                                if (loTail == null)
                                    // loHead赋值为第一个节点
                                    loHead = e;
                                else
                                    // 将节点加在loTail后面
                                    loTail.next = e;
                                loTail = e;
                            }
                            // e的hash和旧容量相与不为0
                            else {
                                // 如果hiTail为空,表示该节点为第一个节点
                                if (hiTail == null)
                                    // hiHead赋值为第一个节点
                                    hiHead = e;
                                else
                                    // 将节点加在hiTail后面
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        // 如果loTail不为空(说明老表的数据有分布到新表上“原索引位置”的节点),则将最后一个节点的next设为空,并将新表上索引位置为“原索引位置”的节点设置为对应的头节点
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead;
                        }
                        // 如果hiTail不为空(说明老表的数据有分布到新表上“原索引+oldCap位置”的节点),则将最后一个节点的next设为空,并将新表上索引位置为“原索引+oldCap”的节点设置为对应的头节点
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

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

tips:扩容resize()的效率很低,如果需要插入大量的值,可以提前设置好容量,避免频繁的扩容,用空间换时间

get()方法:
主要是调用getNode()方法,如果找不到返回null
先调用hash计算哈希值,获取通下标,然后再判断第一个节点是否为红黑树,如果是红黑树,则通过树的方式获取,否则还是按照链表的方式获取

    public V get(Object key) {
        Node<K,V> e;
        return (e = getNode(hash(key), key)) == null ? null : e.value;
    }
    
    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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值