HashMap中add()方法的源码学习

时间:2022-07-23
本文章向大家介绍HashMap中add()方法的源码学习,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

一、HashMap底层数据结构

  • JDK1.7及之前:数组+链表
  • JDK1.8:数组+链表+红黑树

HashMap中实际是维护了一个Node数组,用来存储数据,下面看一下Node源码:

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

简单介绍一下Node中的属性:

1:hash值

2:key-键

3:value-值

4:nest-这个属性值的类型是Node类型,意思是当前节点的下一个节点,从这个属性可以看出在数组的结构上又结合和链表,至于红黑树会在添加数据的时候动态往红黑树转变

二、HashMap add()

  分析一波add()源码,上代码:

//hash值和元素的hashCode()方法相关
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是否为null,如果是,则哈希表未初始化,就对其初始化,初始化大小会默认定位16,当数组储存量 length > table.length*0.75 时,数组会扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //(n - 1) & hash 使用数组长度和hash值做与运算,计算出当前节点应该储存的位置,如果该位置没有元素,就存储元素
        //(n - 1) & hash 运算相当于 hash % n,但是hash后按位与 n-1,比%模运算取余要快
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            
                
            /*
                存入的元素和以前的元素比较哈希值
                    如果哈希值不同,会继续向下执行,把元素添加到集合
                    如果哈希值相同,会调用对象的equals()方法比较
                        如果返回false,会继续向下执行,把元素添加到集合
                        如果返回true,说明元素重复,不存储
            */
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            // 如果数组中的链表已经转为树结构,则使用树类型的put
            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;
                    }
                    // 如果hash值相同,equals也返回true,则表示为相同对象,直接e = p.next覆盖
                    // 如果hash值相同,equals不同,则判定为不一样的对象,则追加新节点到尾部
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 循环替换迭代
                    p = e;
                }
            }
            //如果e不是null,说明有需要覆盖的节点
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 空方法,没实现,LinkedHashMap的时候有用到
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        // 如果新增一个元素后,大小超过了 容量 * 负载因子,则需要扩容
        if (++size > threshold)
            resize();
        // 空方法,没实现
        afterNodeInsertion(evict);
        return null;
    }