HashMap源码分析(jdk1.8)

本文对JDK1.8中的HashMap源码进行分析,涵盖继承关系、Node结构、类的属性、构造函数等内容。介绍了hash、put、resize、get、remove等方法的实现原理,还提及部分红黑树相关代码,如链表树形化判断等,展现了HashMap的高效设计。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

以jdk1.8中的HashMap源码进行分析。

继承关系

public class HashMap<K,V> extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable

其中,AbstractMap是对Map接口骨干实现,以最小化实现Map接口所需工作。

Node结构

是HashMap的静态内部类,实现了Map.Entry接口。

static class Node<K,V> implements Map.Entry<K,V> {
        final int hash; //定位数组索引的位置
        final K key;
        V value;
        Node<K,V> next; //hash值相同的元素通过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;
        }
// 判断两个node是否相等,若key和value都相等,返回true
        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;
        }
    }

类的属性

// 默认容量16,容量需要为2的幂次方。
    static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
//容量上限2^30
    static final int MAXIMUM_CAPACITY = 1 << 30;
//负载因子,默认0.75
    static final float DEFAULT_LOAD_FACTOR = 0.75f;
//树形化门限
    static final int TREEIFY_THRESHOLD = 8;
//恢复链表结构门限
    static final int UNTREEIFY_THRESHOLD = 6;
//最小树形化容量
//HashMap容量大于64,才可能进行树形化,否则只会扩容。
//要求该值不小于4 * TREEIFY_THRESHOLD
    static final int MIN_TREEIFY_CAPACITY = 64;

// 存放元素的数组,大小为2的幂次方
	transient Node<K,V>[] table;
//存放具体元素的集
    transient Set<Map.Entry<K,V>> entrySet;
//元素个数
    transient int size;
//记录结构修改次数,failfast用
    transient int modCount;
//临界值,当容量*负载因子超过临界值,会扩容
    int threshold;
//负载因子
    final float loadFactor;

构造函数

HasMap(int, float)型构造函数

// 满足初始容量不小于0,不大于最大值,填充因子大于0且为数字
    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);
    }

tableSizeFor (cap):返回大于initialCapacity的最小的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;
    }

HashMap(int)型:

    public HashMap(int initialCapacity) {
        this(initialCapacity, DEFAULT_LOAD_FACTOR);
    }

HashMap()型:

    public HashMap() {
        this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
    }

HashMap(Map<? extends K>)型:

    public HashMap(Map<? extends K, ? extends V> m) {
        this.loadFactor = DEFAULT_LOAD_FACTOR;
        //将m中所有元素添加至HashMap中
        putMapEntries(m, false);
    }

putMapEntries将Map中所有元素添加至HashMap中:

final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
        int s = m.size();
        if (s > 0) {
        	//未初始化,s为元素个数
            if (table == null) { // pre-size
                float ft = ((float)s / loadFactor) + 1.0F;
                int t = ((ft < (float)MAXIMUM_CAPACITY) ?
                         (int)ft : MAXIMUM_CAPACITY);
                if (t > threshold)
                    threshold = tableSizeFor(t);
            }
            //初始化大于阈值,扩容
            else if (s > threshold)
                resize();
            //添加
            for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
                K key = e.getKey();
                V value = e.getValue();
                putVal(hash(key), key, value, false, evict);
            }
        }
    }

hash方法

获取key的hashCode(),将其右移16位与原hashCode进行异或运算,返回结果。使数组长度较短时让hashCode的高位也起作用。

    static final int hash(Object key) {
        int h;
        return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
    }

put方法

put方法中调用了putVal:

    public V put(K key, V value) {
    	//hash是针对key计算hashcode()
        return putVal(hash(key), key, value, false, true);
    }

putVal:

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
        Node<K,V>[] tab; Node<K,V> p; int n, i;
        // 判断数组是否为空或者null,否则resize扩容
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        //计算hash值所在数组下标,确定存储在哪个桶里,如果桶为空,新生成一个系欸点放在桶中(直接插入数组中)
        if ((p = tab[i = (n - 1) & hash]) == null)
            tab[i] = newNode(hash, key, value, null);
        //桶中有元素
        else {
            Node<K,V> e; K k;
            // 桶中第一个元素hash相等,key相等
            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;
                    }
                    // 在链表中判断元素key值相等
                    if (e.hash == hash &&
                        ((k = e.key) == key || (key != null && key.equals(k))))
                        break;
                    // 前面是e = p.next, 赋值用于遍历
                    p = e;
                }
            }
            //在链表的第一个节点(数组中)或者在链表中找到了key,hash相等
            //此时e不为null(被赋值为p,或没判断到末尾就相等跳出)
            if (e != null) { // existing mapping for key
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                // 访问后回调
                afterNodeAccess(e);
               	// 返回旧值
                return oldValue;
            }
        }
        // put属于结构性修改
        ++modCount;
        // 判断扩容
        if (++size > threshold)
            resize();
        //插入后回调
        afterNodeInsertion(evict);
        return null;
    }

其中,计算hash值对应桶的下标时,通过:

i = (n - 1) & hash

a % b = (b - 1) & a, when b = 2k
比起取模运算,位运算效率更高。
同时,对于长度为2k的情况,(n - 1)生成111…1的形式,可作为掩码,与hash值进行位与运算时,可以得到较均匀分布的结果。

resize()方法

每次插入操作后都需要判断是否需要扩容。

final Node<K,V>[] resize() {
        Node<K,V>[] oldTab = table; //指向旧的hash桶数组
        int oldCap = (oldTab == null) ? 0 : oldTab.length; //未初始化就设为0
        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 容量*2
        }
        else if (oldThr > 0) // initial capacity was placed in threshold
            newCap = oldThr; //之前的cap为0,threshold不为0,设为thr.
        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]; //新的hash桶数组
        table = newTab; //table指向新数组
        if (oldTab != null) {
            for (int j = 0; j < oldCap; ++j) { //对于旧数组中的每一个桶,遍历
                Node<K,V> e;
                if ((e = oldTab[j]) != null) { //这个桶在j处不为空
                    oldTab[j] = null; //置空,方便gc
                    if (e.next == null) //桶里只有一个Node
                        newTab[e.hash & (newCap - 1)] = e; //对e元素hash求新的存储位置并放进去
                    else if (e instanceof TreeNode) //树节点
                        ((TreeNode<K,V>)e).split(this, newTab, j, oldCap); //离散化
                    else { // 链表形式,设两个链表,分别有头尾指针
                        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) { //最高位为0,插在lo链表尾部
                                if (loTail == null)
                                    loHead = e;
                                else
                                    loTail.next = e;
                                loTail = e;
                            }
                            else {  // 最高位为1,插在hi链表尾部
                                if (hiTail == null)
                                    hiHead = e;
                                else
                                    hiTail.next = e;
                                hiTail = e;
                            }
                        } while ((e = next) != null);
                        if (loTail != null) {
                            loTail.next = null;
                            newTab[j] = loHead; //lo链表连接到原来的j位置
                        }
                        if (hiTail != null) {
                            hiTail.next = null;
                            newTab[j + oldCap] = hiHead; //hi链表连接到j+oldCap位置
                        }
                    }
                }
            }
        }
        return newTab;
    }

上面重新计算hash桶索引的代码:

e.hash & oldCap

在扩容前后,容量变为2倍,(n - 1) & hash实际上是多了一个最高位的bit位,因此做&操作时,如果hash值该位为0,就还是在原来的位置,否则就会在“原位置+旧容量”的位置上。因此在判断应属位置后,分别用两个链表存储扩容后一个旧位置对应两个新位置应有的元素,再插入新数组中。同时,保证新数组中每个桶中的节点数一定不大于旧桶,不会有更严重的冲突。

get方法

get方法是通过getNode来取得元素的。

 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;
        // table已初始化,长度大于0,通过hash找到的桶中元素不为空
        if ((tab = table) != null && (n = tab.length) > 0 &&
            (first = tab[(n - 1) & hash]) != null) {
            if (first.hash == hash && // 第一项元素就相等
                ((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;
    }

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;
        // hash计算的桶有元素
        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; //要移除的node存储下来
                            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; //链表中node指向p.next, 直接跳过node
                ++modCount; //remove是结构性改变
                --size;
                afterNodeRemoval(node); //回调
                return node;
            }
        }
        return null;
    }

部分和红黑树有关的代码:

树的结构: 继承自LinkedHashMap

static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
        TreeNode<K,V> parent;  // red-black tree links
        TreeNode<K,V> left;
        TreeNode<K,V> right;
        TreeNode<K,V> prev;    // needed to unlink next upon deletion
        boolean red;
        TreeNode(int hash, K key, V val, Node<K,V> next) {
            super(hash, key, val, next);
        }

treeifyBin:在插入新元素后判断链表长度,是否需要树形化

    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) { //e为首节点
            TreeNode<K,V> hd = null, tl = null; //树的首尾节点
            do {
                TreeNode<K,V> p = replacementTreeNode(e, null); //该节点转化为TreeNode节点
                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); //树形化
        }
    }

treeify :真正的树形化

        final void treeify(Node<K,V>[] tab) {
            TreeNode<K,V> root = null; //定义根节点
            for (TreeNode<K,V> x = this, next; x != null; x = next) {
                next = (TreeNode<K,V>)x.next; //下一个节点
                x.left = x.right = null;
                if (root == null) { //没有根节点
                    x.parent = null;
                    x.red = false; //当前节点为黑节点
                    root = x; // 根节点指向当前节点
                }
                else { //有根节点
                    K k = x.key; //当前链表节点的key 
                    int h = x.hash; //key对应的hash
                    Class<?> kc = null;
                    for (TreeNode<K,V> p = root;;) { // 从根节点开始遍历
                        int dir, ph; // 记录方向,hash值
                        K pk = p.key;
                        if ((ph = p.hash) > h) //当前树的hash大于链表节点hash
                            dir = -1; //向左
                        else if (ph < h)
                            dir = 1; //向右
                        //两个节点key的hash值相等,comparable比较,tieBreakOrder比较
                        else if ((kc == null &&
                                  (kc = comparableClassFor(k)) == null) ||
                                 (dir = compareComparables(kc, k, pk)) == 0)
                            dir = tieBreakOrder(k, pk);

                        TreeNode<K,V> xp = p; //保存当前树节点
                        // 叶节点
                        if ((p = (dir <= 0) ? p.left : p.right) == null) {
                            x.parent = xp;
                            if (dir <= 0)
                                xp.left = x; //作为左孩子
                            else
                                xp.right = x; //作为右孩子
                            root = balanceInsertion(root, x); //重新平衡
                            break;
                        }
                    }
                }
            }
            //把红黑树的根节点设为其所在的桶的第一个元素
            moveRootToFront(tab, root);
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值