JDK源码解析 - java.util.HashMap

15 篇文章 0 订阅

1.静态变量

  // 6个默认值
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16 右移4位 2的4次方 table数组默认初始容量

static final int MAXIMUM_CAPACITY = 1 << 30; //table数组最大容量

static final float DEFAULT_LOAD_FACTOR = 0.75f; //加载因子

static final int TREEIFY_THRESHOLD = 8; //阈值 当table中元素大于 该值-1,将链表转化为红黑树

static final int UNTREEIFY_THRESHOLD = 6; //扩容时,table中数据小于该值,由红黑树转为链表

static final int MIN_TREEIFY_CAPACITY = 64; //转化为树之前,会判断node中键值对个数是否大于该值,大于该值才会转化树

2.存放键值对的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;
        }

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

3.tableSizeFor

    /**
     * Returns a power of two size for the given target capacity.
     */
    //返回大于参数且最近的2的整数次幂的数
    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;
    }

4.构造方法相关参数

transient Node<K,V>[] table; //存放键值对node节点的数组

transient Set<Map.Entry<K,V>> entrySet;//和遍历有关

transient int size; //大小

transient int modCount; //修改次数

int threshold; //阈值

final float loadFactor; //加载因子

5.构造方法

    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); //阈值为2的幂次方
    }
    
    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }
    
    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);
    }

构造方法只赋值了loadFactorthreshold 2个参数

6.put方法

    public V put(K key, V value) {
        return putVal(hash(key), key, value, false, true);
    }
    
     /**
     * Map.put()方法的实际实现
     *
     * @param hash key的hash值
     * @param key 键值对中的key
     * @param value 键值对中的value
     * @param onlyIfAbsent 如果为true,则键值对中的值已经存在则不修改这个值
     * @param evict 如果为false,则是处于创建模式
     * @return 上一次的value,如果上一次的value不存在,则为null
     */
    final V putVal(int hash, K key, V value, boolean onlyIfAbsent, boolean evict) {
        //tab用于暂存散列表table。p为散列表中对应索引的链表的头节点的指针。n存储tab的长度。i则为命中的散列表的索引
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        //给tab和n赋值
        //当tab为null或者tab的长度n为0时,触发resize()来初始化tab
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //使用(n - 1) & hash(等价于hash%n)计算命中的散列表索引,同时判断散列表对应索引的链表是否存在
        if ((p = tab[i = (n - 1) & hash]) == null)
            //散列表对应索引的链表不存在则创建一个新的链表
            tab[i] = newNode(hash, key, value, null);
        else {//散列表对应索引的链表已存在
            Node<K,V> e; K k;
            // 判断头节点的hash值和key是否与入参的hash值和key一致。需要注意,null的hash值为0
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                // 对应的键值对已经存在,记录下来
                e = p;
            else if (p instanceof TreeNode)//判断对应的链表是否转化为红黑树
                //若是,则直接调用红黑树的putTreeVal()方法
                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开始,所以为阈值-1 
                            // 将链表转化为红黑树
                            treeifyBin(tab, hash);
                        // 中断循环
                        break;
                    }
                    // 判断当前遍历的节点的hash值和key是否与入参的hash值和key一致,即key是否已经存在
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        // key已经存在,中断循环
                        break;
                    // 记录当前遍历的节点
                    p = e;
                }
            }
            if (e != null) { // Map中存在重复的key
                V oldValue = e.value;//记录下旧值
                if (!onlyIfAbsent || oldValue == null)//判断值存在是否可以进行修改以及旧值是否为null
                    e.value = value;//修改该节点的值
                afterNodeAccess(e);// 链表节点的回调方法,此处为空方法
                return oldValue;//返回旧值
            }
        }
        // HashMap发生结构变化,变化次数累加
        ++modCount;
        // 键值对个数自增,同时判断是否达到扩容的阈值
        if (++size > threshold)
            resize();
        // 链表节点的回调方法,此处为空方法
        afterNodeInsertion(evict);
        // 此处返回null是因为链表新增了节点,所以上一次的值必然为null
        return null;
    }

7.resize方法

 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) {
            // 如果大于最大容量(2的30次方),将阈值设置为Integer最大数值。返回原有数组,不扩容
            if (oldCap >= MAXIMUM_CAPACITY) {
                threshold = Integer.MAX_VALUE;
                return oldTab;
            } // 如果新容量大于默认最下容量16并小于最小最大容量。
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                    oldCap >= DEFAULT_INITIAL_CAPACITY) //newCap = oldCap << 1 将原数组大小扩大为2倍
                // 将旧阈值扩大两倍作为新阈值。
                newThr = oldThr << 1;
        } else if (oldThr > 0) // 初始化容器,并设置为阈值
            newCap = oldThr;
        else {               // 初始阈值为零,表示使用默认值初始化
            newCap = DEFAULT_INITIAL_CAPACITY; // 16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
        }
        // 如果新阈值为0。再次用指定的加载因子初始化新阈值。
        if (newThr == 0) {
            // 初始化HashMap指定的加载因子。
            float ft = (float)newCap * loadFactor;
            // 扩容后长度没有超过最大capacity。用计算出来的。如果超过就用Integer的最大值。
            newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
                    (int)ft : Integer.MAX_VALUE);
        }
        // 新阈值生效
        threshold = newThr;
        @SuppressWarnings({"rawtypes","unchecked"})
        // 创建新容量的Node数组
                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;
                // 如果j桶中有数据,先用临时e节点储存
                if ((e = oldTab[j]) != null) {
                    // 该桶和数组连接置空,方便后面GC数组
                    oldTab[j] = null;
                    // 如果该桶就有一个元素,
                    if (e.next == null)
                        // 计算出新数组的位置,并将Node放入
                        newTab[e.hash & (newCap - 1)] = e;
                        // 桶中数据为红黑树。
                    else if (e instanceof TreeNode)
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
                    else { // 链表的散列
                        Node<K,V> loHead = null, loTail = null;// 表示还在原角标位上的node元素
                        Node<K,V> hiHead = null, hiTail = null;// 表示在原角标+oldCapacity位
                        Node<K,V> next;
                        // 依次将原先的节点拿出来重新挂在node中。
                        do {
                            // 保存第二个节点
                            next = e.next;
                            // 根据当前节点hash&oldCapacity整除,来判断该节点在原来的j位置。
                            // 如果有余,就散列到新的j+oldCap位置
                            if ((e.hash & oldCap) == 0) {
                                //loTail在保存node节点的时候,先赋next,然后覆盖loTail,最后next置空
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }// 不整除,就将这一串数据放到j+oldCap位置。
                            else {
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            // 尾节点置null,上一节点和本节点数据相同;
                            loTail.next = null;
                            // 将列表头放入数组的角标微商
                            newTab[j] = loHead;
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead;
                        }
                    }
                }
            }
        }
        return newTab;
    }

8.get方法

    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; //table长度
        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;
    }

9.remove方法

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

10.clear方法

    public void clear() {
        Node<K,V>[] tab;
        modCount++;
        if ((tab = table) != null && size > 0) {
            size = 0; //长度赋空值
            for (int i = 0; i < tab.length; ++i)
                tab[i] = null; //强引用赋为null 由gc自动回收
        }
    }

还有些和红黑树相关方法(水平有限,不写了)…

参考资料:

https://www.cnblogs.com/wlandyy/p/10287186.html
https://blog.csdn.net/qq_42742861/article/details/96651247
https://segmentfault.com/a/1190000018156976#item-2-2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值