HashMap 部分源码解析

HashMap 部分源码解析


在JDK 8 之前,HashMap 的底层实现是数组 + 链表。JDK 8 及之后,HashMap 改为了 数组 + 链表 + 红黑树 的实现方式

属性

    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; // 桶上链表长度大于等于 8 时,且桶容量 大于 64时,链表转化为红黑树

    static final int UNTREEIFY_THRESHOLD = 6; // 桶上红黑树小于等于6时,红黑树转化为链表
 
    static final int MIN_TREEIFY_CAPACITY = 64; // 数组容量大于 64  时,链表才会转化为红黑树
    
    transient Node<K,V>[] table; // 存放数据的数组
    
    transient Set<Map.Entry<K,V>> entrySet;

    transient int size;

    transient int modCount;
    // 扩容阈值,有两种情况
    // 初始化时,大小为 2^x
    // 如果是通过 resize() ,大小 = 数组容量 * 0.75
    int threshold;

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

可以看出每个 Node 节点中包含了四个字段:hash、key、value、next。其中next 表示链表的下一个节点。

构造函数

    public HashMap(int initialCapacity, float loadFactor) {
        // ...... 检查参数是否合法
        if (initialCapacity > MAXIMUM_CAPACITY)
            initialCapacity = MAXIMUM_CAPACITY;

        this.loadFactor = loadFactor;
        this.threshold = tableSizeFor(initialCapacity);
    }

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

由构造函数可以看出,如果调用不带参的构造方法,只会为 负载因子赋值为默认值(0.75)。如果调用了带参的构造方法,会额外使用 tableSizeFor 方法为 阈值 threshold 赋值。该方法会返回一个最接近且大于 initialCapacity 的 2 的幂次方数。具体实现如下:

    /**
     * Returns a power of two size for the given target capacity.
     */
    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;
    }

查询

    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) { // 判断 table 数组是否为空,并且元素值不为空
            if (first.hash == hash && // always check first node 如果第一个节点正好是要找的key,直接返回
                ((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;
    }

从代码中可以总结出 获取元素的步骤如下:

  1. 如果哈希桶为空或者桶中对应元素为空,直接返回空
  2. 如果第一个元素正好时要找的元素,返回
  3. 如果桶中是红黑树结构,按照红黑树的方式递归查找。如果是链表结构,遍历链表查找

新增

    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) // 如果值为 null,添加元素
            tab[i] = newNode(hash, key, value, null);
        else { // 不为 null
            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 如果节点数大于 8,红黑树化
                            treeifyBin(tab, hash);
                        break;
                    }
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k)))) // 如果发现了该键,直接覆盖,break
                        break;
                    p = e;
                }
            }
            if (e != null) { // existing mapping for key 赋值
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null) //onlyIfAbsent为 false时,覆盖
                    e.value = value;
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold) // 如果 size 大于扩容阈值,扩容
            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;
        if (oldCap > 0) {
            if (oldCap >= MAXIMUM_CAPACITY) { // 如果 oldCap 比最大容量还大,threshold 设置为 int 的最大值,返回 oldCap
                threshold = Integer.MAX_VALUE;
                return oldTab;
            }
            // 扩大容量为当前容量的两倍,但不超过 最大容量
            else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
                     oldCap >= DEFAULT_INITIAL_CAPACITY)
                newThr = oldThr << 1; // double threshold 阈值也扩大为当前阈值的两倍
        }
        // 当前数组没有数据,使用阈值比如初始化数组的时候,因为初始化HashMap时并没有初始化数组
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr;
        else {               // zero initial threshold signifies using defaults // 如果初始化值为 0(容量=16,threshold = 16 * 0.75 = 12)
            newCap = DEFAULT_INITIAL_CAPACITY; // 16
            newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY); // 12
        }
        if (newThr == 0) { // 计算扩容阈值,因为上面三个条件中,第二次没有计算 threshold 值
            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;
    }

扩容计算元素的哈希值时,是通过高位运算(e.hash & oldCap)来确定是否需要移动的。高一位为 1,结果为 0时表示在扩容时位置不会发生变化;高一位为 1,结果为 1 时,表示元素扩容时位置发生了变化,新的下标 = 原下标 + 原数组长度

具体步骤如下:

  • 如果 oldCap > 0,扩容为 2 倍(如果没有超过最大值)
  • 否则,如果阈值 > 0,newCap = 阈值
  • 否则(oldCap=0,阈值=0),赋值为默认值

删除

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

通过阅读上面的源码,我们会发现 e.hash & (newCap - 1) 会出现很多次,这是 计算下标的一种方式,这也是为什么数组长度一定要位 2^n 的原因。

数组长度减一后,可以得到高位全为 0,低位全为 1 的情况,这是与 hash 进行按位与操作,就相当于取了 hash 值的低位,这样不仅可以快速获取 key 对应的下标,还使数组元素可以分布均匀。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值